Built-in Promises
Mongoose asynchronous operations, like. Save () and queries, return promises/a+ conformant Promises. This means the can do things like Mymodel.findone ({}). then () and yield Mymodel.findone ({}). EXEC () (If you ' re using CO ).
This means that you can do something like Mymodel.findone ({}). then () and yield Mymodel.findone ({}). exec (if you're using CO)
For backwards compatibility, Mongoose 4 returns mpromise promise by default.
var New Band ({ "guns N ' Roses", Members : [' AXL ', ' Slash '] }); var promise = gnr.save (); instanceof require (' mpromise ')); Promise.then (function (doc) { "guns N ' Roses"); });
Queries is not promises
Mongoose query is not promise. But it has yield and async/await. Then () method. If you need a sound promise, use the. Exec () method.
varquery = Band.findone ({name: "Guns N ' Roses"}); Assert.ok (! (QueryinstanceofRequire (' mpromise '))); //a query is not a fully-fledged promise, but it does has a '. Then () '.Query.then (function(DOC) {//Use Doc }); //'. EXEC () ' gives you a fully-fledged promise varPromise =query.exec (); Assert.ok (PromiseinstanceofRequire (' mpromise ')); Promise.then (function(DOC) {//Use Doc });
Insert into your Promises library
Update on Mongoose 4.1.0
In cases where mpromise satisfies basic usage, advanced users may want to insert their favorite ES6-style promise libraries such as Bluebird, or just use native ES6 promise. Set the Mongoose. Promise gives you a favorite ES6-style Promise constructor and then mongoose uses it.
varquery = Band.findone ({name: "Guns N ' Roses"}); //Use native promisesMongoose. Promise =Global. Promise; Assert.equal (Query.exec (). constructor, Global. Promise); //Use BluebirdMongoose. Promise = require (' Bluebird ')); Assert.equal (Query.exec (). Constructor, require (' Bluebird ')); //Use Q. Note, **must** use ' require (' Q '). Promise '.Mongoose. Promise = require (' q ')). Promise; Assert.ok (Query.exec ()instanceofRequire (' Q ')). makepromise);
MongoDB-driven Promise
Mongoose. The Promise property setting Mongoose uses promise. However, this does not affect the underlying MongoDB driver. If you use the underlying driver, such as Mondel.collection.db.insert (), you need to do some extra work to change the underlying promise library. Note that the following code assumes mongoose >= 4.4.4.
var uri = ' mongodb://localhost:27017/mongoose_test '; // Use Bluebird var options = {promiselibrary:require (' Bluebird ')}; var db = mongoose.createconnection (URI, options); = Db.model (' band-promises ', {name:string}); Db.on (function() { assert.equal (Band.collection.findOne (). Constructor, require ( ' Bluebird '); });
Mongoose Documents (10) Promises