What does the populate function in mongoose do?
In Article
document, you are storing userId of the users.
Now while querying Article
document, with articles you want to get users for each then you can use populate.
Now when you access articles[index].user
, then it will return object instead of ObjectId
value (_id
property of user).
Second argument defines that which field should be retrieved in User
object. Here it is displayName
. So it will retrieve _id
and displayName
of User
. If you want to exclude _id you can specify "-_id displayName"