我已存儲在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例子,使用它會很感激 –