Update meteor collection without removing or overriding existing fields

拟墨画扇 提交于 2019-12-06 03:13:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16929284/update-meteor-collection-without-removing-or-overriding-existing-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!