Skip to content

Instantly share code, notes, and snippets.

@crguezl
Created April 14, 2016 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crguezl/165cfec398c5576b6d4d88f3e4b6f204 to your computer and use it in GitHub Desktop.
Save crguezl/165cfec398c5576b6d4d88f3e4b6f204 to your computer and use it in GitHub Desktop.
mongoose query without immediate callback
(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(); } );
});
});
})();
@crguezl
Copy link
Author

crguezl commented Apr 14, 2016

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:

  • is passed, the operation will be executed immediately with the results passed to the callback.
  • is not passed, an instance of Query is returned, which provides a special query builder interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment