我的数据库集合:

获奖者:

{
    "_id": {
        "$oid": "5bd58921fb6fc074abb12ce8"
    },
    "id": "301",
    "winner": [
        "101",
        "102"
    ]
}


优胜者模型在这里

var winner = new Schema({
  _id: String,
  id: String,
  winner:[ String ]
},
  {
  strict: false
});
var Winner = mongoose.model('winner', winner);


获奖者集合中获奖者数组中的值101和102应该用{“ sample”:“ data”}更新

 var result = [{"id": "101" },{"id": "102" }];
 var length = result.length;
 for(var i=0;i<length;i++)
  {
  Winner.updateMany(
    { "winner" : result[i].id },
    { $set: { "winner" : result[i] } }, function (err,output) {
      if(err)
      {
      console.log(err);
      }
      else
      {
      console.log(output);
      }
    }
 );
}


预期产量:

优胜者收藏集应更新为

获奖者:

{
    "_id": {
        "$oid": "5bd58921fb6fc074abb12ce8"
    },
    "id": "301",
    "winner": [
        {"sample":"data"},
        {"sample":"data"}
    ]
}

最佳答案

首先,您要插入字符串数组,但是稍后您要存储对象数组。猫鼬模式将不允许这样做。您必须将架构从winner:[ String ]更新为winner:[{sample: String}],并首先存储对象数组。

{
    "_id": {
        "$oid": "5bd58921fb6fc074abb12ce8"
    },
    "id": "301",
    "winner": [
        {"sample": "101"},
        {"sample": "102"}
    ]
}


编辑:您也想更新

Winner.updateMany(
    { "winner" : result[i].id },
    { $set: { "winner" : result[i] } },
.
.




Winner.updateMany(
    { "winner.sample" : result[i].id },
    { $set: { "winner" : result[i] } },
.
.

09-30 21:26