5

I don't know why but if i try to update an existing field using the $set method, any existing fields are replaced in the same context.

For example. Say i have an existing collection with the following fields.

Name of collection: Ticket

{profile: {name: "Test", placement: 1}, requestor: _id}

When i attempt to add/update fields to this collection like this:

 var ticket = Meteor.tickets.findOne({_id: ticketID});

 if(ticket){
    Meteor.users.update(ticket, {
                        $set: profile: {name: "Test2", new_fields: "value"}
                    });
 }

The collection gets updated and the name field changes but placement is removed and no longer there. This is also true if i remove the name field. How do we properly update a meteor collection without having to keep passing the same structure over and over?

Warz
  • 7,386
  • 14
  • 68
  • 120

2 Answers2

9

Just do this:

$set: {"profile.name": "Test2", "profile.new_fields": "value"}

I.e. You were replacing the whole hash. Instead you can update the fields within the hash.

BraveNewCurrency
  • 12,654
  • 2
  • 42
  • 50
  • Just as you were posting this, i found this. http://stackoverflow.com/questions/10290621/how-do-i-partially-update-an-object-in-mongodb-so-the-new-object-will-overlay. Will accept in a few minutes. Thanks – Warz Jun 04 '13 at 23:56
0

if the field you want to change have a unique index, you can modify that particular field to what you want without destroying the remaining information in the field.

db.artists.find()

{"_id":ObjectId("1"),"name":"A1","media_id":["m1","m2" ]}

{"_id":ObjectId("2"),"name":"A2","media_id":["m2","m3"]}

{"_id":ObjectId("3"),"name":"A3","media_id":["m3","m1","m2"]}

db.artists.ensureIndex({"name":1})

db.artists.update(
    {name:"A1"},
    {$set: { name:"A4"}},
    { upsert: true }
    )

b.artists.find()

{"_id":ObjectId("1"),"name":"A4","media_id":["m1","m2" ]}

{"_id":ObjectId("2"),"name":"A2","media_id":["m2","m3"]}

{"_id":ObjectId("3"),"name":"A3","media_id":["m3","m1","m2"]}

I am myself quite new in MongoDB but this worked pretty well for me.

Ar maj
  • 1,974
  • 1
  • 16
  • 16