Warz
Warz

Reputation: 7756

Update meteor collection without removing or overriding existing fields

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?

Upvotes: 5

Views: 5146

Answers (2)

Ar maj
Ar maj

Reputation: 2064

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.

Upvotes: 0

BraveNewCurrency
BraveNewCurrency

Reputation: 13065

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.

Upvotes: 9

Related Questions