【发布时间】:2022-01-06 13:05:45
【问题描述】:
我尝试使用 Mongoose 和 NodeJS 更新 MongoDB 集合,但有时会出现以下错误,但并非总是出现:
MongoServerError: 在 findAndModify :: 期间计划执行程序错误,由 :: 位置运算符未从查询中找到所需的匹配项。
这是我的代码:
NodeJS
try {
this.myArrayUpdate = { 'description': 'test' };
this.update = { $set:
{ 'myArray.$': this.myArrayUpdate }
};
const cardId = ObjectId("61d6e320520fac65775a7ba8")
const userId = ObjectId("61a8e433648e1963ae7358be");
const filter = {
userId: userId,
'myArray._id': cardId,
};
const options = {
upsert: true,
new: true
};
MyCollection
.findOneAndUpdate(
filter,
this.update,
options,
)
.then ( () => {
return res.status(204).json({ message: 'MyCollection updated ' });
});
} catch (error) {
throw error;
}
MongoDB
{
"_id" : ObjectId("61a8e433648e1963ae7358be"),
"myArray" : [
{
"description" : "test",
"starting" : null,
"ending" : null,
"_id" : ObjectId("61d6e320520fac65775a7ba8")
},
{
"description" : "test 2",
"starting" : null,
"ending" : null,
"_id" : ObjectId("61d6e320520fac657812991a")
},
],
}
如果找到答案的一部分,每次我更新我的子文档数组时,_id 都会改变,所以这就是为什么会出现错误,如果我更新我的页面就不会再出现错误了!
是否有可能在更新子文档数组时不创建新的_id?
感谢您的回答,
大卫
【问题讨论】: