• 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. Css - 渲染按钮

    基本的css3按钮渲染 <style type="text/css"> background: #f7f7f7; /* for Webkit */ background ...

  2. Unattend.xml应答文件制作(WISM)-- 转自爱做梦的鱼

    将制作好的应答文件unattend.xml拷贝到模板机sysprep目录下,然后在cmd下运行(unattend.xml文件可自定义名称)   sysprep /generalize /oobe /s ...

  3. iOS textFiled 在storyBoard中的使用

    step 1. 在UITableViewCotroller的xib中设置一个静态表格,在Utilities里选择属性检查器(第四个啦)设置属性,content : static cells. styl ...

  4. VMware 虚拟机使用 NAT 方式联网

    选择要设置的虚拟主机: 点击右键,选择 “属性”,查看 “网络适配器”: 此时选择的连接方式是 “Host-only”,在 Host-only 模式中,所有的虚拟系统是可以相互通信的,但虚拟系统和真实 ...

  5. ThinkPHP 源码分析之常量 IS_AJAX

    在控制器中判断请求是否是通过 AJAX 提交,ThinkPHP(3.2.2)中在 ThinkPHP/Library/Think/App.class.php (Line:49) 中定义了常量 IS_AJ ...

  6. 理解 Python 中的 *args 和 **kwargs

    Python是支持可变参数的,最简单的方法莫过于使用默认参数,例如: def test_defargs(one, two = 2): print 'Required argument: ', one ...

  7. TextView实现圆角效果

    自定义一个Xml样式: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android ...

  8. Grand Theft Auto V 图形研究(2)

    原文链接 http://www.adriancourreges.com/blog/2015/11/02/gta-v-graphics-study-part-2/   Level of Detail 如 ...

  9. 推荐给开发者的20个优秀PHP框架

    推荐给开发者的20个优秀PHP框架 来源:developerslane   时间:2015-01-13 19:48:06   阅读数:111916 分享到:14 [导读] PHP是非常受欢迎并且很有影 ...

  10. Shell-bash中特殊字符汇总[转]

    转自http://www.linuxidc.com/Linux/2015-08/121217.htm 首先举例一个bash脚本 #!/bin/bash file=$1 files=`find / -n ...