this mongodb document, need add data:
{ "_id" : "7kufvmqfyyeukfp68", "target" : { "10" : "true", "id" : "epce6fbahx9kekjum" } }
i need update existing fields in target
or add them, if not exist. tried:
var result = { "30": "true", "id" : "epce6fbahx9kekjum" }; collection.upsert( { _id: id }, { $set: { target: result } } );
but 10
replaced 30
, expect result:
{ "_id" : "7kufvmqfyyeukfp68", "target" : [{ "10" : "true", "30" : "true", "id" : "epce6fbahx9kekjum" }] }
it seems want array of objects updated. array target
field make sure type array in schema. update array select array id or field of choice.
this code finds field , adds "30" : "true",
, leaves other information in object inside array. hope helps.
var userschema = new mongoose.schema({ name: string, target : [] }) var user = mongoose.model("user", userschema); //creat documenent var user1 = new user({ name : "jack", target :[{ "10" : "true", "id" : "epce6fbahx9kekjum" }] }) user1.save(user1, function(err, user){ console.log(user) }) user.findoneandupdate( {"name" : "jack"}, {safe : true, upsert : true, new :true}, function(err, model){ model.target[0]["30"] = "true" console.log(model.target) } )
Comments
Post a Comment