1

I have a method written with node as follows to query from the collection

  query: function (model, conditon, options) {
            console.log(conditon, options);
            return new Promise(function (resolve, reject) {
                options = options || {};

                model.find(conditon, {}, options).exec(function (error, data) {
                    if (error)
                        reject(error);
                    resolve(data);
                })
            })
        }

i want to fetch the data for the following query,

db.getCollection('_event').find({}).sort({'metadata.popularity': 1}).limit(10)

How should i modify the above method to support this query?

This is how i call the query function from another file,

 dbService.query(eventModel, { 'eventId': idRetrieved }, {});
 }).then(data => dbService.disconnectDb(data))
    .then(data => callback(data))
     .catch((error) => {
          dbService.disconnectDb(error).then(error => {
          console.log(error);
          callback({}, error);
})
2
  • exec returns a promise if you don't provide a callback, so why are you creating your own promise? Anyway, where are the sort and limit parameters coming from? Commented Mar 3, 2017 at 4:43
  • @JohnnyHK limit and sort i executed on mongo db, i want to know how to change the above code to support that? Commented Mar 3, 2017 at 4:45

1 Answer 1

1

Just call sort and limit on the Query object returned from the find call.

But you don't need to create your own Promise as exec already returns a promise if you don't provide a callback.

function (model, condition, options, sort, limit) {
    return model.find(condition, {}, options).sort(sort).limit(limit).exec();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.