mongoose的promise(转发)
- Switching out callbacks with promises in Mongoose
Published on July 28, 2015
Working with promises and mongoose just became a whole lot easier with the 4.1 release, which added the ability to specify alternative promise libraries. Prior to that, promise support was limited to the mpromise way of using promises. For some folks, including myself, this meant there wasn't a friendly .catch
method available to the promise chain. In this post, I'll quickly cover how to switch over to other supported promise libraries and show how using promises can clean up your mongoose callbacks.
Normally, when using mongoose, you just need to require it. In order to switch out the promise provider, you'll also need to require the promise library and pointmongoose.Promise
to it. In the following example, I set the promise library to bluebird:
var mongoose = require('mongoose');
// set Promise provider to bluebird
mongoose.Promise = require('bluebird');
Here's the example for using native promises or q
:
// q
mongoose.Promise = require('q').Promise;
// native promises
mongoose.Promise = global.Promise;
That's as simple and non-hacky as one could hope for. Next up, I'll show what typical mongoose callbacks look like and how you can swap those out for promises. In these last examples, I'll look up a user by id, update the user's name, and save it:
// error first callback style
User.findById('123', function(err, user) {
if (err) {
return console.log('error:', err);
}
user.name = 'Robert Paulson';
user.save(function(err) {
// yet another err object to deal with
if (err) {
return console.log('error:', err);
}
console.log('updated user: ' + user.name);
// do something with updated user
});
});
The above callback example shows the first level of nesting and multiple error handlers. That's not too bad, but with more logic it can easily become visually overwhelming. In the last example, I'll show what the same task looks like using promises. We'll switch to using Model queries that return a promise via the .exec()
function.
var promise = User.findById('123').exec();
promise.then(function(user) {
user.name = 'Robert Paulson';
return user.save(); // returns a promise
})
.then(function(user) {
console.log('updated user: ' + user.name);
// do something with updated user
})
.catch(function(err){
// just need one of these
console.log('error:', err);
});
Note that there was only one error handler for both of the promises,findById(id).exec()
and user.save()
. For me, the benefit of using promises is really in the ability to read what's going on in the code and to consolidate error handling into one place with the option to break that out if needed. If that interests you, give promises in mongoose a try
mongoose的promise(转发)的更多相关文章
- 关于学习js的Promise的心得体会
最近一直在研究js的Promise对象,其中有一篇blog写得比较通俗易懂,转发如下: http://www.cnblogs.com/lvdabao/p/es6-promise-1.html 参照上面 ...
- Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose
参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...
- mongodb入门笔记
mongodb作为nosql中排名第一的数据库,近年来使用的人数越来越多,作为开发人员,非常有必要了解下mongodb数据库.下面就给大家介绍下mongodb数据库的基本知识,有不对的地方欢迎指正,Q ...
- [Node] Catch error for async await
When we try to do MongoDB opration, mongoose return Promise, we can use async/await to simply the co ...
- [js高手之路]Node.js+jade+express+mongodb+mongoose+promise实现todolist
promise主要是用来解决异步回调问题,其实还有好几种比promise更好的方案,后面再说,这节,我们先用promise来改造下,我以前写的一篇文章[js高手之路]javascript腾讯面试题学习 ...
- Primise --(mongoose's default promise library)
今天在学nodejs的时候,遇到一个错误;刚开始完全不知道说的是什么,为什么会出现这个错误 DeprecationWarning: Mongoose: mpromise (mongoose's def ...
- Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
操作数据库的时候,老是提示:Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your ow ...
- 深入理解jQuery、Angular、node中的Promise
最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供 ...
- Mongoose与bluebird结合使用实例
nodejs的所有调用几乎是全异步的,而所有的IO操作也都是通过回调函数才能知道结果. 如果一个异步调用依赖另一个异步调用,如果没有Promise的话,有可能陷入传说中的回调地狱. bluebird实 ...
随机推荐
- CreateFeatureClass 异常,尝试读取或写入受保护的内存 Access
在创建要素时出现如下异常,百思不得其解. 后经过多次试验,发现文件名改为其他的就可以了.自出的文件名为"第3条",后将文件名改为"A3"等,则可正常创建. 后再 ...
- ICursor查询后的排序问题
为某表做剔除整合处理,各行相关.起初使用 ICursor pCursor = pTable.Search(null,false); 语句查询,ICursor的第一行并没有指向表的第一行,虽然不是第一行 ...
- CVE-2014-4113 windows通杀本地提权0day
这个0day的发现挺有意思的,是老外CrowdStrike 发现的,被老外监测程序发现显示从WEBSHELL使用Win64.exe来提升权限. 原文地址:http://blog.crowdstrike ...
- RestSharp用法小结
今天有空,小结一下RestSharp的用法. RestSharp内置了XML和JSON的反序列化(deserializers ). application/json – JsonDeserialize ...
- 【iHMI43 4.3寸液晶模块】demo竖屏例程(版本1.01)发布
============================== 技术论坛:http://www.eeschool.org 博客地址:http://xiaomagee.cnblogs.com 官方网店:h ...
- c3p0配置 initialPoolSize 和minPoolSize 可以设为0吗?设0有坏处吗?
c3p0配置 initialPoolSize 和minPoolSize 可以设为0吗?设0有坏处吗? c3p0配置 initialPoolSize 和minPoolSize 可以设为0吗?设0有坏处吗 ...
- 《Java核心技术卷一》笔记 多线程
有时,我们需要在一个程序中同时并行的处理多个任务,如播放器一边要播放音乐同时还要不断更新画面显示,或者是一边执行耗时任务,UI还能一边继续响应各种事件.还有的时候,一个任务需要很长时间才能完成,如果分 ...
- twitter storm源码走读之2 -- tuple消息发送场景分析
欢迎转载,转载请注明出处源自徽沪一郎.本文尝试分析tuple发送时的具体细节,本博的另一篇文章<bolt消息传递路径之源码解读>主要从消息接收方面来阐述问题,两篇文章互为补充. worke ...
- Windows2008 R2修改3389端口教程
默认的3389端口有必要修改么,这个端口,我建议是修改一下为好,最好改大一点,这样安全性会高一点,但然面对高手级攻击,就没有用了,通常高手级过NMAP扫描一个你的IP地址,端便全然显现出来了,好了,下 ...
- shell执行mysql操作
http://ully.iteye.com/blog/1226494 http://www.jb51.net/article/55207.htm shell执行mysql操作 mysql -hhos ...