Query.prototype.populate()
Parameters
path «Object|String» either the path to populate or an object specifying all parameters
[select] «Object|String» Field selection for the population query
[model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s
ref
field.[match] «Object» Conditions for the population query
[options] «Object» Options for the population query (sort, etc)
[options.path=null] «String» The path to populate.
[options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make
populate()
retainnull
andundefined
array entries.[options.getters=false] «boolean» if true, Mongoose will call any getters defined on the
localField
. By default, Mongoose gets the raw value oflocalField
. For example, you would need to set this option totrue
if you wanted to add alowercase
getter to yourlocalField
.[options.clone=false] «boolean» When you do
BlogPost.find().populate('author')
, blog posts with the same author will share 1 copy of anauthor
doc. Enable this option to make Mongoose clone populated docs before assigning them.[options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing MongoDB query syntax, or a function that returns a filter object.
[options.options=null] «Object» Additional options like
limit
andlean
.
Returns:
- «Query» this
Specifies paths which should be populated with other documents.
Example:
let book = await Book.findOne().populate('authors');
book.title; // 'Node.js in Action'
book.authors[0].name; // 'TJ Holowaychuk'
book.authors[1].name; // 'Nathan Rajlich'
let books = await Book.find().populate({
path: 'authors',
// `match` and `sort` apply to the Author model,
// not the Book model. These options do not affect
// which documents are in `books`, just the order and
// contents of each book document's `authors`.
match: { name: new RegExp('.*h.*', 'i') },
sort: { name: -1 }
});
books[0].title; // 'Node.js in Action'
// Each book's `authors` are sorted by name, descending.
books[0].authors[0].name; // 'TJ Holowaychuk'
books[0].authors[1].name; // 'Marc Harter'
books[1].title; // 'Professional AngularJS'
// Empty array, no authors' name has the letter 'h'
books[1].authors; // []
Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.