Mongoose: multiple query populate in a single call

In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as

Person.find({})
 .populate('books movie', 'title pages director')
 .exec()

However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:

Person.find({})
 .populate('books', 'title pages')
 .populate('movie', 'director')
 .exec()

which gives me the expected result and queries.

But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.


Solution 1:

After looking into the sourcecode of mongoose, I solved this with:

var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];

Person.find({})
 .populate(populateQuery)
 .execPopulate()

Solution 2:

you can also do something like below:

{path:'user',select:['key1','key2']}