mongoose 文档(十) Promises
2016-02-20 00:41
537 查看
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')); });
相关文章推荐
- django的models部分使用小结
- Atitit.go语言golang语言的新的特性 attilax总结
- Atitit.go语言golang语言的新的特性 attilax总结
- Atitit.go语言golang语言的新的特性 attilax总结
- 查看google chrome和firefox上的cookie
- codeforces 630D Hexagons!
- ZOJ 2855 Google Map
- 几种malloc实现原理 ptmalloc(glibc) && tcmalloc(google) && jemalloc(facebook)
- NetLogon事件ID:5722
- NetLogon事件ID:5723
- golang走起(四)执行命令行
- golang走起(三)list简单使用和interface{}
- GoDaddy开通中文客服电话,沟通不再是问题
- golang走起(二)对象与指针二
- golang走起(一)对象与指针
- Google反编译新工具——Enjarify
- uva 11054 Wine trading in Gergovia
- [golang note] 数组切片
- golang笔记——IDE
- mongo 命令