[英]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.