- 英文原版
- 关于中文文档
- 快速上手
- 模式(Schemas)
- 模式类型(SchemaTypes)
- 连接(Connections)
- 模型(Models)
- 文档 (Documents)
- 子文档(Subdocuments)
- 查询 (queries)
- 验证 (validation)
- 中间件 (middleware)
- 填充 (Populate)
- 鉴别器 (Discriminators)
- 插件
- AWS Lambda
- API 文档
- Schema
- Connection
- Document
- Model
- Query
- Aggregate
- SchemaType
- VirtualType
- Error
- Version Compatibility
- FAQ
[
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.
var gnr = new Band({
name: "Guns N' Roses",
members: ['Axl', 'Slash']
});
var promise = gnr.save();
assert.ok(promise instanceof Promise);
promise.then(function (doc) {
assert.equal(doc.name, "Guns N' Roses");
});
[
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.
var query = Band.findOne({name: "Guns N' Roses"});
assert.ok(!(query instanceof Promise));
// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (doc) {
// use doc
});
// `.exec()` gives you a fully-fledged promise
var promise = query.exec();
assert.ok(promise instanceof Promise);
promise.then(function (doc) {
// use doc
});
[
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.
var query = Band.findOne({name: "Guns N' Roses"});
// Use bluebird
mongoose.Promise = require('bluebird');
assert.equal(query.exec().constructor, require('bluebird'));
// Use q. Note that you **must** use `require('q').Promise`.
mongoose.Promise = require('q').Promise;
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.
var uri = 'mongodb://localhost:27017/mongoose_test';
// Use bluebird
var options = { promiseLibrary: require('bluebird') };
var db = mongoose.createConnection(uri, options);
Band = db.model('band-promises', { name: String });
db.on('open', function() {
assert.equal(Band.collection.findOne().constructor, require('bluebird'));
});