這是我的貓鼬模式:
userId 是 Okta 為用戶組態檔生成的唯一編號。'''
var book_listSchema = new mongoose.Schema({
userId:{type: String, required: true},
first_name: { type: String, required: true},
last_name:{ type: String, required: true},
newList: [{
list_name: String,
books:
[{
book_name: {type: String, required: true},
book_author: {type: String, required: true},
date_added: {type: Date, default: Date.now},
date_finished: {type: Date, default: Date.now},
}]}],
});
'''
這是我用來查找和更新的代碼,將一本書添加到書籍陣列中。
'''
book_list.findOneAndUpdate({"userId": req.userContext.userinfo.sub, newList:{"newList.list_name": list_name}}, {$push:{books:{book_name: title, book_author:author, date_added: new Date()}}}
'''
book 陣列沒有更新,newList 中的每個物件都有 list_name,并且有不同的串列,每個串列都有自己的 books 陣列,因此添加書籍時需要更新正確的串列。
樣本資料集:
'''
_id:625c81d7622b044fb297ce54
userId:"00uvgyn7OikAwud6"
first_name:"John"
last_name:"Smith"
newList:Array
0:Object
list_name:"read"
books:Array
0:Object
book_name:"The Great Gatsby"
book_author:"Francis Scott Fitzgerald"
date_added:2022-04-19T00:43:24.248 00:00
_id:625e05ac083663dc44f37804
date_finished:2022-04-19T00:43:24.252 00:00
_id:625e05ac083663dc44f37803
__v:0
'''
uj5u.com熱心網友回復:
正確的方法是:
db.collection.update({
userId: "00uvgyn7OikAwud6",
newList: {
$elemMatch: {
list_name: "read"
}
}
},
{
$push: {
"newList.$.books": {
book_name: "a new book",
book_author: "some author",
date_added: new Date()
}
}
})
或以您的代碼方式
db.collection.update({
userId: req.userContext.userinfo.sub,
newList: {
$elemMatch: {
list_name: list_name
}
}
},
{
$push: {
"newList.$.books": {
book_name: title,
book_author: author,
date_added: new Date()
}
}
})
$elemMatch 允許您在同一陣列元素中匹配多個組件,然后您可以使用 $push 在陣列中添加特定物件。
您可以在此處運行它以檢查相同的查詢https://mongoplayground.net/p/YnzDRfhwpEt
您還可以在此鏈接中查看 $elemMatch 的檔案。
如果您遇到任何問題,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459248.html
標籤:javascript 表示 猫鼬 猫鼬模式
