更新文档时将对象推送到数组属性

时间:2017-04-14 18:25:37

标签: mongodb mongoose mongoose-schema

我使用mongoose作为架构&持久层。

在现有文档中向项目属性添加项目时,它会失败:错误等于2.23.1,raw等于null

知道为什么会这样吗?

更新代码

{ n: 0, nModified: 0, ok: 1 }

架构定义

 let concreteAnswer = {
  questionId: 1,
  answer: {
    rating: 34
  }
};

Participation.update(
  {
    _id: 'some-unique-id',
    'answers.$.instrumentName': 'some-instrument-name' // instrumentName is unique within the answers array
  },
  {
    $push: {"answers.$.concreteAnswers" : concreteAnswer}
  },
  (err, raw) => {
    console.log(`error occured! raw: ${raw}, error: ${err}`);
  }
);
数据库中的

文档

var ParticipationSchema = new Schema({
    answers: [{
      instrumentName: { type: String, enum: validInstruments },
      concreteAnswers: [{
        questionId: Number,
        answer: {}
      }]
    }]
    // further attributes omitted for readability
},
{
    timestamps: true
});
var Participation = mongoose.model('Participation', ParticipationSchema);

2017-04-16:根据@ VEERAM评论更改的更新代码

{
    "_id": "some-unique-id",
    "answers": [
      {
        "instrumentName": "some-instrument-name",
        "_id": "another-unique-id",
        "concreteAnswers": []
      },
      // etc.
}

我也刚刚意识到,现在操作正常(即文档将在数据库中更新),但它仍会在错误处理中执行Participation.update( { _id: mongoose.Types.ObjectId('some-unique-id'), 'answers.instrumentName': 'some-instrument-name' }, { $push: {"answers.$.concreteAnswers" : concreteAnswerDto} }, // ERR HANDLING AS ABOVE }

0 个答案:

没有答案