gpt4 book ai didi

node.js - 更新引用文档数组时 mongoose 中的 DivergentArrayError

转载 作者:可可西里 更新时间:2023-11-01 09:51:31 35 4
gpt4 key购买 nike

我在 mongoose 中定义了一个模式,如下所示:

var VolunteerSchema = new Schema ({
......
other fields
.....
preferLocations:[{
type: Schema.ObjectId,
ref: 'Location'
}]
.....
});

我正在使用 volunteer.save() 方法来更新模型。

更新到 volunteer 模型时,出现如下错误:

{ [DivergentArrayError: For your own good, using `document.save()` to update an
array which was selected using an $elemMatch projection OR populated using skip,
limit, query conditions, or exclusion of the _id field when the operation resul
ts in a $pop or $set of the entire array is not supported. The following path(s)
would have been modified unsafely:
preferLocations
Use Model.update() to update these arrays instead.]
message: 'For your own good, using `document.save()` to update an array which
was selected using an $elemMatch projection OR populated using skip, limit, quer
y conditions, or exclusion of the _id field when the operation results in a $pop
or $set of the entire array is not supported. The following path(s) would have
been modified unsafely:\n preferLocations\nUse Model.update() to update these a
rrays instead.',
name: 'DivergentArrayError' }

在更新位置时,我收集数组中的 _ids 字段并分配给 preferLocations,如下所示:

volunteer.preferLocations = locationIdsArray;

删除此行时我没有收到错误。我做错了什么?

最佳答案

在投影中使用 $elemMatch 时,请勿使用 document.save()。相反,使用 Model.update() 手动更新您的文档。在你的情况下,你应该尝试

 volunteer.findOneAndUpdate(
{
_id: ObjectId("567452bae5b25d6e6c1a0f7e"),
localization: { '$elemMatch': { language: 'de' } }
},
{
$set: { 'localization.$.name' : "Neuer Name" }
}).exec(//...
});

click这里有更多细节

关于node.js - 更新引用文档数组时 mongoose 中的 DivergentArrayError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380919/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com