我似乎根本無法讓這個貓鼬$pull操作起作用。我嘗試了很多解決方案,但最終還是想使用原子操作來實作這一點,因為這是我其余代碼中的設計模式。
在我的List架構中,我有一個Item物件陣列。每個Item物件都有一個陣列,Notes其中都是字串值。創建、讀取和更新這些Notes陣列一直沒有問題。但我似乎無法讓洗掉功能正常作業。
架構:
串列
const listSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "Users"
},
name: {
type: String
},
items: {
type: Array,
default: [itemSchema]
}
});
物品
const itemsSchema = {
item: String,
style: String,
moved: Boolean,
notes: Array
};
示例檔案:
_id: 6186940ce10fbd7cec9fb01f
items: Array
0: Object
notes: Array
0: "Updated again x2"
1: "Test one to delete edit"
2: "New one"
_id: 6186d98dcef2ae43605becc4
item: "Test 1"
style: ""
moved: false
1: Object
notes: Array
_id: 6186d98fcef2ae43605becc5
item: "Test 2"
style: ""
moved: false
2: Object
notes: Array
_id: 6186d991cef2ae43605becc6
item: "Test 3"
style: ""
moved: false
3: Object
notes: Array
0: "Add from none"
1: "typing a really long sentence here to see what happens when I get to t..."
2: "Test"
_id: 6186d994cef2ae43605becc7
item: "Test 4"
style: ""
moved: false
user: 611083d8baed4458d8dcd273
name: "Nov-06-2021"
__v: 0
方法:
創建
List.findOneAndUpdate(
{ "user": req.user.id, "name": list, "items._id": ObjectId(id) },
{ "$push": { "items.$.notes": newNote } },
{ new: true },
(err, newList) => {}
)
更新
List.findOneAndUpdate(
{ "user": req.user.id, "name": list, "items._id": ObjectId(id) },
{ "$set": { "items.$.notes.$[note]": newNoteText } },
{
arrayFilters: [{"note": note}],
new: true
},
(err, newList) => {}
)
洗掉(不作業)
List.findOneAndUpdate(
{ "user": req.user.id, "name": list, "items._id": ObjectId(id) },
{ "$pull": { "items.$.notes.$[note]": note } },
{
arrayFilters: [{"note": note}],
new: true
},
(err, newList) => {}
)
當前的 Delete 代碼塊接近于我希望我的解決方案的樣子。根據所有權利,以及我讀過的所有內容,它應該已經可以使用了。誰能告訴我什么會起作用,可能為什么這目前不起作用?
I have tried many solutions including using $in, $[], $elemMatch, and a bunch more outside the box solutions. I don't see why $push and $set work without issue, but $pull is deciding to do nothing.
The current response I get from MongoDb with this operation doesn't include an error message, but the returned newList is a null value, and no change is reflected in my DB. I am currently on the latest version of mongoose: 5.13.13.
uj5u.com熱心網友回復:
解決這個問題的方法是$[note]從我的運算子中洗掉 ,因為$pull需要一個陣列來操作,而不是陣列物件。
我之前肯定嘗試過,之前我的請求正文來自前端。axios.delete但是,我沒有對 an 使用正確的語法,這是我的主要問題。
解決方案
List.findOneAndUpdate(
{ "user": req.user.id, "name": list, "items._id": ObjectId(id) },
{ "$pull": { "items.$.notes": note } },
{ new: true },
(err, newList) => {}
)
我洗掉$[note]了一個變數,因為$pull對整個notes陣列進行操作。因此,我不再需要 ,arrayFilters因為它已經在尋找note變數了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355647.html
上一篇:總結貓鼬中的值
