我已存储在MongoDB中的一个文件:如何找到在猫鼬ID子文档,并排除某些领域
shop: {
_id: '...'
title: 'my shop'
users: [
{
_id: '...',
name: 'user1',
username: '...'
},
{
_id: '...',
name: 'user2',
username: '...'
}
]
}
我用这个查询他的ID来获得子文档用户:
Shop.findOne({'users._id': userId}, {'users.$': 1}, function (err, user) {
console.log(user);
});
输出:
{ _id: ...,
users:
[{
name: 'user1',
username: '...',
_id: ...
}]
}
我怎样才能筛选结果只返回用户名。 我现在就这样做的方式:
Shop.findOne({'users._id': userId}, {'users.$': 1}, function (err, shop) {
shop = shop.toObject()
user = shop.users[0]
filtered = {
name: user.name
}
callback(filtered);
});
但有一个更好的方式来做到这一切在查询?
我不明白如何使用这种方法,也许litte例子,使用它会很感激 –