what does populate in mongoose mean?

Populate will automatically replace the specified path in the document, with document(s) from other collection(s).

Your example

Story.findOne({ title: Nintendo })

will return a Story of this kind:

{
  _creator : A0jfdSMmEJj9, // example value
    title    : Nintendo,
    fans     : [r432i900fds09809n, fdsjifdsjfueu88] // example values
  }
}

That kind of request would be enough when we don’t care about the author or the fans, only their IDs.

But in the case where we need that _creator‘s name, we would need to make another request to find it in the database.

In Mongoose we have function populate() that we can chain to our previous request to directly get that information in our answer without doing an additional request.

Story.findOne({ title: Nintendo }).populate('_creator')

will return

{
  _creator : {
       _id : A0jfdSMmEJj*9,
       name: Sai,
       age: 100,
       stories : [fdsfdsfdsew38u, 89hr3232, ...]
    },
    title    : Nintendo,
    fans     : [r432i900fds09809n, fdsjifdsjfueu88]
  }
}

If that’s too much information, and his age and name are enough but we don’t want the stories that he wrote, populate can take another argument containing the field that we need.

Story.findOne({ title: Nintendo }).populate('_creator', 'name age')

will return

{
  _creator : {
       name: Sai,
       age: 100,
    },
    title    : Nintendo,
    fans     : [r432i900fds09809n, fdsjifdsjfueu88]
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)