• Switching out callbacks with promises in Mongoose

Published on July 28, 2015

mongo node mongoose promises

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(转发)的更多相关文章

  1. 关于学习js的Promise的心得体会

    最近一直在研究js的Promise对象,其中有一篇blog写得比较通俗易懂,转发如下: http://www.cnblogs.com/lvdabao/p/es6-promise-1.html 参照上面 ...

  2. Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose

    参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...

  3. mongodb入门笔记

    mongodb作为nosql中排名第一的数据库,近年来使用的人数越来越多,作为开发人员,非常有必要了解下mongodb数据库.下面就给大家介绍下mongodb数据库的基本知识,有不对的地方欢迎指正,Q ...

  4. [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 ...

  5. [js高手之路]Node.js+jade+express+mongodb+mongoose+promise实现todolist

    promise主要是用来解决异步回调问题,其实还有好几种比promise更好的方案,后面再说,这节,我们先用promise来改造下,我以前写的一篇文章[js高手之路]javascript腾讯面试题学习 ...

  6. Primise --(mongoose's default promise library)

    今天在学nodejs的时候,遇到一个错误;刚开始完全不知道说的是什么,为什么会出现这个错误 DeprecationWarning: Mongoose: mpromise (mongoose's def ...

  7. 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 ...

  8. 深入理解jQuery、Angular、node中的Promise

    最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供 ...

  9. Mongoose与bluebird结合使用实例

    nodejs的所有调用几乎是全异步的,而所有的IO操作也都是通过回调函数才能知道结果. 如果一个异步调用依赖另一个异步调用,如果没有Promise的话,有可能陷入传说中的回调地狱. bluebird实 ...

随机推荐

  1. SparkContext.setCheckpointDir()

    class SparkContext extends Logging with ExecutorAllocationClient Main entry point for Spark function ...

  2. HTML&CSS----练习(运算符)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. 【iM_VGA模块】运行 ucgui 演示!

    挂在 iCore2 双核心板上的 VGA模块,跑 ucgui DEMO 演示.大家看看! ============================== 技术论坛:http://www.eeschool ...

  4. java字符串抉择

    下面我们就字符串连接方面分析. 1.String 打开String的源码,如图所示 会发现存储字符串的字符数值是final常量.再看String的构造方法,发现String的value值在构造方法就确 ...

  5. CruiseControl.Net学习记录

    一.下载 官网 二.安装 本文版本:1.8.5.0 运行安装程序,按照提示"下一步”,直到完成即可. 安装完毕之后, 生成一个windows服务,CruiseControl.NET Serv ...

  6. uploadify 3.2 后台动态传参数

    最近在弄一个上传的小功能,需要往后台传递一些动态参数,网上有一些传参数可能是因为版本不对也没成功.仔细看了官网的一些说明,搞定了. 3.2中传递参数用的的是'formData':{'somekey': ...

  7. Gitolite配置管理和GIT基本操作

    简述公司版gitolite的项目配置与管理 1. 基于秘钥对的管理 1.1 客户端(需要访问代码库的机器)生成秘钥对,采用RSA加密ssh-keygen -t rsa -f path_to_store ...

  8. python 操作excel 使用笔记

    写入excel, 保存的过程中需要注意,保存格式xls后缀,如果用xlsx会报错 def set_style(name,height,bold=False): """&q ...

  9. Bootstrap页面布局18 - BS导航路径以及分页器

    导航路径:又叫“面包屑”,功能是让用户知道所处的位置. <!--面包屑--> <ul class='breadcrumb'> <li><a href='#'& ...

  10. php concurrence