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() retain null and undefined array entries.

  • [options.getters=false] «boolean» if true, Mongoose will call any getters defined on the localField. By default, Mongoose gets the raw value of localField. For example, you would need to set this option to true if you wanted to add a lowercase getter to your localField.

  • [options.clone=false] «boolean» When you do BlogPost.find().populate('author'), blog posts with the same author will share 1 copy of an author 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 and lean.

Returns:
  • «Query» this

Specifies paths which should be populated with other documents.

Example:

  1. let book = await Book.findOne().populate('authors');
  2. book.title; // 'Node.js in Action'
  3. book.authors[0].name; // 'TJ Holowaychuk'
  4. book.authors[1].name; // 'Nathan Rajlich'
  5. let books = await Book.find().populate({
  6. path: 'authors',
  7. // `match` and `sort` apply to the Author model,
  8. // not the Book model. These options do not affect
  9. // which documents are in `books`, just the order and
  10. // contents of each book document's `authors`.
  11. match: { name: new RegExp('.*h.*', 'i') },
  12. sort: { name: -1 }
  13. });
  14. books[0].title; // 'Node.js in Action'
  15. // Each book's `authors` are sorted by name, descending.
  16. books[0].authors[0].name; // 'TJ Holowaychuk'
  17. books[0].authors[1].name; // 'Marc Harter'
  18. books[1].title; // 'Professional AngularJS'
  19. // Empty array, no authors' name has the letter 'h'
  20. 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.