[英]Why findOne({ id }) is not working properly in mongoose 6.012
[英]findOne mongoose query is not working properly
我已经使用express创建了这个网络应用程序。 我也有猫鼬模型:
{
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
notes: [{
name: { type: String, required: true }
}]
}
当我尝试在数组中查找对象时(Notes)->
modelName.findOne({ "notes:" {$elemMatch: {"_id": req.body.id } }})
.exec()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
我得到一个用户的整个模型对象,而不是一个注释。 这是我得到的结果:
{
"_id": "5c51dd8be279e9016716e5b9",
"username": "user1",
"password": "",
"notes": [
{
"_id": "5c51dd8be279e901671gagag",
"name": "name of note1"
},
{
"_id": "5c51ff8be279e901671gagag",
"name": "name of note"
},
{
"_id": "5c51dd8be2131501671gagag",
"name": "name of note"
}
]
}
但是,我的期望是收到以下信息:
{
"_id": "5c51dd8be279e901671gagag",
"name": "name of note1"
}
PS:它不是此答案Mongoose Mongodb查询对象数组的重复项。 我已经尝试过使用该问题中的代码,但这并不能解决我的问题
findOne()工作正常。 findOne()返回与指定查询匹配的任何文档,而不是文档的一部分。 如果只需要该文档的一部分,则必须将其分为两部分...
modelName.findOne({ "notes": {$elemMatch: {"_id": req.body.id } }})
.exec()
.then(result => {
// Will get an array of notes whose _id === req.body.id
const resNote = result.notes.filter(n => n._id === req.body.id);
console.log(resNote);
})
.catch(err => {
console.log(err);
});
请参阅此处的文档。 如果您注意到的话,它提到函数“找到一个文档”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.