solarc
solarc

Reputation: 5738

Replace object from array inside a Meteor Collection

I have a collection called Tiers with this schema:

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

How can I replace an object inside the prizes array by the pos field?

I'm trying with this:

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

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

But I get this exception: MongoError: Field name duplication not allowed with modifiers

Upvotes: 1

Views: 464

Answers (1)

Disposer
Disposer

Reputation: 6371

This could be your answer

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

Upvotes: 2

Related Questions