jgr0
jgr0

Reputation: 727

Bluebird Promises in waterline .native() sailsjs with sails-mongo

According to the .native() documentation, the way to use .native() query for sails-mongo is :

Pet.native(function(err, collection) {
    if (err) return res.serverError(err);
    collection.find({}, {
        name: true
    }).toArray(function (err, results) {
          if (err) return res.serverError(err);
               return res.ok(results);
       });
});

How can I avoid callback here and use promises instead. Note that I have to use aggregate queries, so have to use .native()

Upvotes: 0

Views: 535

Answers (1)

user93
user93

Reputation: 1866

As mentioned here Open bootstrap.js in config and monkey patch all methods with promise like this

module.exports.bootstrap = function(cb) {
var Promise = require('bluebird');

Object.keys(sails.models).forEach(function (key) {
    if (sails.models[key].query) {
        sails.models[key].query = Promise.promisify(sails.models[key].query);
    }
});

cb();  };

On the bonus side you get to use the latest version of bluebird with all models. Hope it helps

Upvotes: 2

Related Questions