Built-in Promises
Mongoose 异步操作,像 .save() 和 queries,返回 Promises/A+ conformant promises. This means that you can do things like MyModel.findOne({}).then() and yield MyModel.findOne({}).exec() (if you‘re using co).
这就是说你可以做一些像MyModel.findOne({}).then() 和 yield MyModel.findOne({}).exec()(如果你在用co)
为了向后兼容,mongoose 4默认返回mpromise promise。
var gnr = new Band({ name: "Guns N‘ Roses", members: [‘Axl‘, ‘Slash‘] }); var promise = gnr.save(); assert.ok(promise instanceof require(‘mpromise‘)); promise.then(function (doc) { assert.equal(doc.name, "Guns N‘ Roses"); });
Queries are not promises
mongoose查询不是promise。可是它有 yield 和 async/await 的 .then() 方法。如果你需要健全的promise,用.exec()方法。
var query = Band.findOne({name: "Guns N‘ Roses"}); assert.ok(!(query instanceof require(‘mpromise‘))); // 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 require(‘mpromise‘)); promise.then(function (doc) { // use doc });
插入到你的 Promises 库
在mongoose 4.1.0更新
在mpromise满足基本使用的情况下,高级用户可能想插入他们喜爱的ES6风格的Promise库如bluebird,或只是使用原生的ES6 promise。设置mongoose.Promise 给你喜欢的ES6风格的promise构造函数然后mongoose会使用它。
var query = Band.findOne({name: "Guns N‘ Roses"}); // Use native promises mongoose.Promise = global.Promise; assert.equal(query.exec().constructor, global.Promise); // 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);
MongoDB驱动的promise
mongoose.Promise属性设置mongoose使用promise。可是,这不影响底层MongoDB驱动。如果你使用底层驱动,例如Mondel.collection.db.insert(),你需要做点额外工作来改变底层promise库。注意,下面的代码假设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‘)); });
时间: 2024-11-07 12:33:45