Erik Aybar

Using ES6 Promises Instead of Callbacks for Mongoose Queries

October 24, 2015

Mongoose queries traditionally follow the typical node.js callback pattern. Thanks to Mongoose 4.2+ and ES6 Promises (available in node 4.x) these can be rewritten using a much more pleasant (and powerful IMO) pattern using promises. By default, these query methods return a Promise.

Using callbacks

someMongooseModel.find(someInput, function(err, results) {
  if (err) {
  /* No error. Proceed as planned. */

Using Promises


Making use of the actual native Promise that ES6 provides, requires very little setup thanks to Mongoose exposing mongoose.Promise

// Set mongoose.Promise to any Promise implementation
mongoose.Promise = Promise;

Here is a snapshot from a less trivial example showing how clean/nice it can be making use of the Promise in the context of a simple RESTful CRUD API built w/ Express, MongoDB, and Mongoose.

RESTful CRUD API built w/ Express, MongoDB, and Mongoose.

Just a quick tip, that I’ve recently discovered. Hopefully I can get around to piecing together a more complete example from my recent experiments with Express/Mongoose!

Erik Aybar

👋🏽 Hi! I'm Erik Aybar. I'm a software person working remotely from St. George, Utah. This is my blog.