mongoose find populate field code example

Example 1: mongoose populate

Story.
  findOne({ title: /casino royale/i }).
  populate('author', 'name'). // only return the Persons name
  exec(function (err, story) {
    if (err) return handleError(err);

    console.log('The author is %s', story.author.name);
    // prints "The author is Ian Fleming"

    console.log('The authors age is %s', story.author.age);
    // prints "The authors age is null'
  });

Example 2: mongodb populate document

Story.
  findOne({ title: 'Casino Royale' }).
  populate('author').
  exec(function (err, story) {
    if (err) return handleError(err);
    console.log('The author is %s', story.author.name);
    // prints "The author is Ian Fleming"
  });

Example 3: Return certain fields with populate from mongoose

Model
.find(query)
.populate({
  path: 'key_with_ref',
  model: 'model_name',
  select: { 'field_name': 1,'field_name':1},
})
 
-OR-

Model
.find(query)
.populate({
  path: 'key_with_ref',
  model: 'model_name',
  select: 'field_name, field_name',
})

Tags:

Misc Example