我似乎根本无法让这个mongoose$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代码块接近于我希望我的解决方案的样子。无论如何,我所读到的一切,它应该已经起作用了。有人能告诉我什么是有效的吗?可能还有为什么目前不起作用?
我尝试过许多解决方案,包括使用$in
、$[]
、$elemMatch
,以及更多开箱即用的解决方案。我不明白为什么$push
和$set
可以毫无问题地工作,但$pull
决定什么都不做。
我通过此操作从MongoDb获得的当前响应不包括错误消息,但返回的newList
是null
值,并且在我的DB中没有反映任何更改。我目前正在使用最新版本的猫鼬:5.13.13
。
解决方案是从我的运算符中删除$[note]
,因为$pull
需要一个数组来操作,而不是数组对象。
我以前肯定尝试过,在我的请求体出现来自前端的问题之前。然而,我没有为axios.delete
使用正确的语法,这是我的主要问题。
解决方案
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
变量。