node.js - Push new items into JSON array -
let's table inside collection:
{ "_id" : objectid("557cf6bbd8efe38c627bffdf"), "name" : "john doe", "rating" : 9, "newf" : [ "milk", "eggs", "beans", "cream" ] }
once user types in input, sent node server, , node server adds item list "newf"
, sent mongodb
, saved. i'm trying use update, can change values inside of table, i'm not sure how add new items onto list. did $push
inside mongodb shell
, not sure how on node.
here's snippet of code:
db.collection('connlist').update({ _id: new objectid("e57cf6bb28efe38c6a7bf6df")}, { name: "johndoe", rating: 9, newf: ["milk, eggs", "beans"] }, function(err,doc){ console.log(doc); });
well syntax adding new items same in shell:
// make sure imported "objectid" var objectid = require('mongodb').objectid; db.collection('conlist').update( { "_id": new objectid("e57cf6bb28efe38c6a7bf6df") }, { "$push": { "newf": { "$each": [ "cream", "butter" ] } } }, function(err,numaffected) { // in callback } )
or perhaps use .findoneandupdate()
if want return modified document instead of making alteration.
of course use $push
, possibly $each
allows multiple array elements added when adding array. if want "unique" items use $addtoset
operation allows.
and speaking other items should use $set
or other operators in update portion of document. without these operators "replacing" document content whatever structure place in "update" portion of statement.
Comments
Post a Comment