• 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. Scrum会议2(Beta版本)

    组名:奋斗吧兄弟 组长:王森 组员:张政.张金生.林莉.胡丽娜 代码地址:HTTPS:https://git.coding.net/jx8zjs/llk.git SSH:git@git.coding. ...

  2. MSF命令 收集

    一.msfconsole ?   帮助菜单 back 从当前环境返回 banner   显示一个MSF banner cd   切换目录 color   颜色转换 connect   连接一个主机 e ...

  3. setInterval 启用和停止,见代码

    <title></title>    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="t ...

  4. Android系统目录结构

    Android系统编译后生成三个映像文件,都是用cpio打包,gzip压缩的. ramdisk.img     文件系统,包含/system, /data, /bin等目录.kernel启动时负责初始 ...

  5. 《你不知道的JavaScript》读书笔记(一)作用域

    名词 引擎:从头到尾负责整个 JavaScript 程序的 编译 及 执行 过程. 编译器:负责 语法分析 及 代码生成. 作用域:负责收集并维护由所有声明的标识符(变量)组成的一系列查询,并实施一套 ...

  6. WordPress工作原理之程序文件执行顺序

    在了解WordPress挂载机制时,一直有一个疑惑,到底是WordPress的内核源文件先执行还是主题文件里functions.php文件先执行.为了解决这个问题,想了解WordPress的工作原理, ...

  7. [转]通过Mesos、Docker和Go,使用300行代码创建一个分布式系统

    http://www.csdn.net/article/2015-07-31/2825348 [编者按]时下,对于大部分IT玩家来说,Docker和Mesos都是熟悉和陌生的:熟悉在于这两个词无疑已成 ...

  8. ArcMap 标注、注记、图形文本

    标注.注记.图形文本 2016年8月10日10:29 ArcMap中怎样向地图添加文本,其中标注与注记是重点内容,此处对此进行总结. 参考链接: ①地图文本基本词汇: 什么是文本? ArcGIS 提供 ...

  9. MySql解决插入中文乱码问题

    在dos中登陆mysql 后输入: // 查看数据使用的所有编码show variables like 'character%';// 修改客户端的编码 为 gbkset character_set_ ...

  10. The Producer-Consumer Relationship

    //Listing 3-1. The Producer-Consumer Relationship Version 1 public class PC { public static void mai ...