猫鼬从填充阵列
问题描述:
选择字段我有一个JSON结构是这样的:猫鼬从填充阵列
// Users Collection
[{
"id": "1",
"email": "[email protected]",
"contacts": [
{
"user": "2", // reference
"nickname": "blub"
},
{
"user": "3", // reference
"nickname": "blub"
},
],
"otherfield": "anything"
}]
的User
对象包含一个数组contacts
这基本上代表引用Users
的列表。为了允许为每个用户存储额外的数据(如nickname
),我有一个对象数组,而不是一个ObjectId数组。
现在我想通过指定要解析的字段来填充联系人(例如,ID和电子邮件)。因此,预期输出是这样的:
{
"id": "1",
"email": "[email protected]",
"contacts": [
{
"user": {
"id": "2",
"email": "[email protected]",
// without other fields
},
"nickname": "blub"
}
],
"otherfield": "anything"
}
我已经试过这样的事情
User.findById(id)
.populate('contacts.user')
.select('contacts.user.email')
但后来我的联系人数组只包含一个空的对象。
另外,如果我试试这个:
User.findById(id).populate({
path: 'contacts.user',
select: 'email'
})
结果只是没有任何人口父用户:
{
email: "[email protected]",
id: "1"
}
答
最后我发现我在documentation忽略(谢谢@Mikey)
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'
})
谢谢。这是行得通的。 –