更新引用文档数组时mongoose中的DivergentArrayError

时间:2015-02-07 10:14:54

标签: node.js mongodb mongoose meanjs

我在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;

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

1 个答案:

答案 0 :(得分:1)

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

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

click更多详情