I have a JSON structure like this:
// Users Collection
[{
"id": "1",
"email": "[email protected]",
"contacts": [
{
"user": "2", // reference
"nickname": "blub"
},
{
"user": "3", // reference
"nickname": "blub"
},
],
"otherfield": "anything"
}]
The User object contains an array contacts which basically represents a list of referenced Users. To allow storing additional data (like the nickname) per user I have an array of objects and not an array of ObjectIds.
Now I would like to get the contacts populated with specifying the fields to resolve (id and email for example). So the expected output is something like this:
{
"id": "1",
"email": "[email protected]",
"contacts": [
{
"user": {
"id": "2",
"email": "[email protected]",
// without other fields
},
"nickname": "blub"
}
],
"otherfield": "anything"
}
I have tried something like this
User.findById(id)
.populate('contacts.user')
.select('contacts.user.email')
But then my contacts array contains only empty objects.
Also if I try this:
User.findById(id).populate({
path: 'contacts.user',
select: 'email'
})
The outcome is just the parent user without any population:
{
email: "[email protected]",
id: "1"
}