Mongoose distinct with promises

965 Views Asked by At

i use when.js as a promise library for mongoose and try to get distinct filed of collection and return result as promise

 mongoose.Promise= require("when");

 function getPromisedDistinct(startDate, endDate) {
    return when.promise(function(resolve, reject) {
        $log.distinct("keys", {
                datetime: {
                    "$gte": startDate,
                    "$lt": endDate
                }
            }).exec()
            .then(function(res) {
                return resolve(res);
            });
    });
 }

however getPromisedDistinct is resolved with promise function

function (resolve, reject) {
    if (!_this.op) {
      callback && callback(null, undefined);
      resolve();
      return;
    }

    _this[_this.op].call(_this, function(error, res) {
      if (error) {
        callback && callback(error);
        reject(error);
        return;
      }
      callback && callback.apply(null, arguments);
      resolve(res);
    });
  }

edit #1 getPromisedDistinct is called as

    function agg(day, startDate, endDate) {
      return when.promise(function(resolve, reject) {
        getPromisedDistinct(startDate, endDate).then(function(keys) {
            log.data("keys is : \n" + licence_keys);
        }).otherwise(function(keys) {
            return reject(err);
        });
    });
}

why this not resolved to value?

1

There are 1 best solutions below

3
On

You've instructed Mongoose to use when.js for its Promise library. If this works as it does with native promises (and seemingly bluebird and q) you don't need to wrap queries in a promise, mongoose will do that for you (once you use exec()) so your code could be written as such:

function getPromisedDistinct(startDate, endDate) {
    return $log.distinct("keys", {
                datetime: {
                    "$gte": startDate,
                    "$lt": endDate
                }
            }).exec()
    });
 }

You can do the same with your agg function.

As @robertklep pointed out in the comments there is no need to include a then block in getPromisedDistinct because it's unnecessary clutter (see promise anti-patterns. You are already returning the promise object with return $log.distinct... and then accessing that value in your agg function.

It's worth taking note of Mongoose's documentation on plugging in a promises library:

Mongoose tests with ES6 native promises, bluebird, and q. Any promise library that exports an ES6-style promise constructor should work in theory, but theory often differs from practice. If you find a bug, open an issue on GitHub