Node.js findOne()返回整个文档,而不是单个对象
我正在尝试使用Node.js findOne()返回整个文档,而不是单个对象,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在尝试使用findOne()查询这组数据: 我想使用\u Id作为过滤器从项数组返回单个对象。我就是这样做的: exports.deleteItem = (req, res, next) => { User.findOne({ 'wardrobe.items': { $elemMatch: { "_id": "5c1a4b7d482bf501ed20ae4a",} } }, (err, item) => { console.log(item); if (e
findOne()
查询这组数据:
我想使用\u Id
作为过滤器从项
数组返回单个对象。我就是这样做的:
exports.deleteItem = (req, res, next) => {
User.findOne({ 'wardrobe.items': { $elemMatch: { "_id": "5c1a4b7d482bf501ed20ae4a",} } }, (err, item) => {
console.log(item);
if (err) {
return console.log("error: " + err);
}
res.redirect('/wardrobe');
});
};
但是,console.log(item)
返回整个文档,如下所示:
{ wardrobe: { items: [ [Object], [Object] ] },
tokens: [],
_id: 5c1a4ba1482bf501ed20ae4b,
email: 'another@new.email',
password:
'$2a$10$quEXGjbEMX.3ERdjPabIIuMIKu3zngHDl26tgRcCiIDBItSnC5jda',
createdAt: 2018-12-19T13:46:09.365Z,
updatedAt: 2018-12-19T13:47:30.123Z,
__v: 2 }
我希望最终使用它删除单个项目,因此我需要从子文档中筛选到单个对象。关于您的问题:
MongoDB始终返回与查询匹配的完整对象,除非添加指定应返回哪些字段的投影。
如果确实只想返回嵌套对象,可以使用聚合管道和$replaceRoot操作符,如下所示:
User.aggregate([
// you can directly query for array fields instead of $elemMatching them
{ $match: { 'wardrobe.items._id': "5c1a4b7d482bf501ed20ae4a"}}},
// this "lifts" the fields wardrobe up and makes it the new root
{ $replaceRoot: {newRoot: '$wardrobe'}
// this "splits" the array into separate objects
{ $unwind: '$items'},
// this'll remove all unwanted elements
{ $match: { 'items._id': "5c1a4b7d482bf501ed20ae4a" },
},
])
这应该只返回想要的项目
不过需要注意的是:如果您打算从数组中删除元素,我建议您看看$pull操作,如果元素符合特定条件,它可以从数组中删除元素:
太棒了-$pull方法正是我想要的。谢谢没问题,很高兴我能帮忙!
User.aggregate([
// you can directly query for array fields instead of $elemMatching them
{ $match: { 'wardrobe.items._id': "5c1a4b7d482bf501ed20ae4a"}}},
// this "lifts" the fields wardrobe up and makes it the new root
{ $replaceRoot: {newRoot: '$wardrobe'}
// this "splits" the array into separate objects
{ $unwind: '$items'},
// this'll remove all unwanted elements
{ $match: { 'items._id': "5c1a4b7d482bf501ed20ae4a" },
},
])
User.update(
{ 'wardrobe.items._id': "5c1a4b7d482bf501ed20ae4a"},
{ $pull: { 'wardrobe.items': {_id: "5c1a4b7d482bf501ed20ae4a"}},
{ multi: true }
)