Built-in Promises - 图1mongoose

Built-in Promises - 图2mongoose

[

Built-in Promises ](#built-in-promises)

Mongoose async operations, like .save() and queries, return ES6 promises. This means that you can do things like MyModel.findOne({}).then() and await MyModel.findOne({}).exec() (if you're using async/await.

  1. var gnr = new Band({
  2. name: "Guns N' Roses",
  3. members: ['Axl', 'Slash']
  4. });
  5. var promise = gnr.save();
  6. assert.ok(promise instanceof Promise);
  7. promise.then(function (doc) {
  8. assert.equal(doc.name, "Guns N' Roses");
  9. });

[

Queries are not promises ](#queries-are-not-promises)

Mongoose queries are not promises. However, they do have a .then() function for yield and async/await. If you need a fully-fledged promise, use the .exec() function.

  1. var query = Band.findOne({name: "Guns N' Roses"});
  2. assert.ok(!(query instanceof Promise));
  3. // A query is not a fully-fledged promise, but it does have a `.then()`.
  4. query.then(function (doc) {
  5. // use doc
  6. });
  7. // `.exec()` gives you a fully-fledged promise
  8. var promise = query.exec();
  9. assert.ok(promise instanceof Promise);
  10. promise.then(function (doc) {
  11. // use doc
  12. });

[

Plugging in your own Promises Library ](#plugging-in-your-own-promises-library)

If you're an advanced user, you may want to plug in your own promise library like bluebird. Just set mongoose.Promise to your favorite ES6-style promise constructor and mongoose will use it.

  1. var query = Band.findOne({name: "Guns N' Roses"});
  2. // Use bluebird
  3. mongoose.Promise = require('bluebird');
  4. assert.equal(query.exec().constructor, require('bluebird'));
  5. // Use q. Note that you **must** use `require('q').Promise`.
  6. mongoose.Promise = require('q').Promise;
  7. assert.ok(query.exec() instanceof require('q').makePromise);

[

Promises for the MongoDB Driver ](#promises-for-the-mongodb-driver)

The mongoose.Promise property sets the promises mongoose uses. However, this does not affect the underlying MongoDB driver. If you use the underlying driver, for instance Model.collection.db.insert(), you need to do a little extra work to change the underlying promises library. Note that the below code assumes mongoose >= 4.4.4.

  1. var uri = 'mongodb://localhost:27017/mongoose_test';
  2. // Use bluebird
  3. var options = { promiseLibrary: require('bluebird') };
  4. var db = mongoose.createConnection(uri, options);
  5. Band = db.model('band-promises', { name: String });
  6. db.on('open', function() {
  7. assert.equal(Band.collection.findOne().constructor, require('bluebird'));
  8. });