Created
April 14, 2016 22:13
-
-
Save crguezl/165cfec398c5576b6d4d88f3e4b6f204 to your computer and use it in GitHub Desktop.
mongoose query without immediate callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
"use strict"; | |
const util = require('util'); | |
const mongoose = require('mongoose'); | |
mongoose.connect('mongodb://localhost/chuchu'); | |
const CardSchema = mongoose.Schema({ | |
"rank" : String, | |
"suit" : String, | |
}); | |
const Card = mongoose.model("Card", CardSchema); | |
let c1, c2, c3, c4; | |
Card.remove().then( () => { | |
c1 = new Card({"rank":"ace", "suit":"spades ♠" }); | |
c2 = new Card({"rank":"2", "suit":"hearts ♥" }); | |
c3 = new Card({"rank":"3", "suit":"clubs ♣" }); | |
c4 = new Card({"rank":"4", "suit":"diamonds ♦" }); | |
let p1 = c1.save(function (err) { | |
if (err) { console.log(`Hubieron errores:\n${err}`); return err; } | |
}); | |
let p2 = c2.save(function (err) { | |
if (err) { console.log(`Hubieron errores:\n${err}`); return err; } | |
}); | |
let p3 = Card.create(c3, function (err, x) { | |
if (err) { console.log(`Hubieron errores:\n${err}`); return err; } | |
}); | |
let p4 = Promise.all([p1, p2, p3]).then( (value) => { | |
let query = Card.find({suit: /spa|hea/}); | |
query.select('rank suit'); | |
query.exec((err, cards) => { | |
if (err) { console.log("ERROR: " + err); } | |
let c = 1; | |
cards.forEach(function (card) { | |
console.log (`${c++}: ${card.rank} of ${card.suit}`); | |
}); | |
}).then( function() { mongoose.connection.close(); } ); | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In mongoose 4, a Query has a
.then()
function, and thus can be used as a promise.Any model method which involves specifying query conditions can be executed two ways:
When a
callback
function:callback
.