node.js - single key value update inside array object -
i have trying update single key value array object inside mongodb collection. updates value single key value.
previous json data inside mongodb
result: [ { "firstname": a, "lastname": b, "age": 5 } ] "_id" : "582187d461cc8230bf0aba03"
what doing updating single key value want update single key value firstname : d , need remaining value must same(persist). got changed , single key value pair updated.
{ result: [ { "first name": } ] "_id" : "582187d461cc8230bf0aba03" }
both lastname , age gone. using node js update collection.
using script
var query = {"_id" : "582187d461cc8230bf0aba03"}; var arr = []; userobj = { firstname : b }; arr.push(userobj); update = { result : arr }; var = options = {new : true, upsert : true}; user.findoneandupdate(query, update, options, function(err, result) { if(err); console.log(err); res.send(result); }
there command can update single key value , value persist in collection
yes, default when update, replace document document b.
you want use $set operator update specific fields instead of replacing entire document.
so instance if have:
{ _id: 123, first_name: "john", last_name: "smith", phone_number: "(123)456-7890" }
and do
db.user.update({_id: 123}, {first_name: "bob"})
you replace whole document , get:
{ _id: 123, first_name: "bob" }
but if do:
db.user.update({ _id: 123 }, { $set: { first_name: "bob" } })
you expected result of:
{ _id: 123, first_name: "bob", last_name: "smith", phone_number: "(123)456-7890" }
in case, can try this:
var obj = { firstname: b }; user.findoneandupdate(query, {$set: obj}, options, function(err, result)
Comments
Post a Comment