How should I properly use populate with mongoose? How should I properly use populate with mongoose? mongoose mongoose

How should I properly use populate with mongoose?


You need to get the order right of defining query options then executing, and chainable APIs such as mongoose Query can't know what additional methods you might call AFTER the query fires. So when you pass the callback to .find, mongoose sends the query right away.

Pass a callback to find

  • query defined by arguments to find
  • since callback is there, query immediately executes and issues command to DB
  • then .populate happens, but it has no effect as the query has already been sent to mongo

Here's what you need to do:

Project.find(query, {}, {    sort: {        _id: -1    }}).populate("milestones").exec(function (error, results) {    callback(results);});

Or a little more readable:

Project    .find(query)    .sort('-_id')    .populate('milestones')    .exec(function(error, results) {                          callback(results);    });

Omit callback and use .exec

  • query passed to .find creates query object with parameters
  • additional chained calls to .sort, .populate etc further configure the query
  • .exec tells mongoose you are done configuring the query and mongoose issues the DB command