从Meteor Collection中的数组替换对象

时间:2014-11-13 14:21:44

标签: mongodb meteor

我有一个名为Tiers的集合,具有此架构:

{
  "_id" : "u7fF2gjig3AXsnYBb",
  "prizes" : [
    {
      "_id" : "8h5b4QCd4fj7n7yek",
      "pos" : 1,
      "prize" : "prize 0"
    },
    {
      "_id" : "ZXK5is9ExpdAJJqJ5",
      "pos" : 2,
      "prize" : "prize 1"
    },
    {
      "_id" : "eWdbxQJ5oaM2xnX8v",
      "pos" : 4,
      "prize" : "prize 2"
    }
  ]
}

如何用pos字段替换prizes数组中的对象?

我正在尝试这个:

var pos = 4;
var newPrize = {_id: Random.id(), pos: pos, prize: prize};

Tiers.update({_id: tierId}, {
  $pull: {prizes: {pos: pos}},
  $push: {prizes: newPrize}
});

但是我得到了这个例外:MongoError: Field name duplication not allowed with modifiers

1 个答案:

答案 0 :(得分:2)

这可能是你的答案

db.test.update(
{
    _id : tierId,
    'prizes.pos': 1
},
{
    $set : {'prizes.$': newPrize}
}
)