node.js - How to check before updating an array element in MongoDB/NodeJS -


in sample document, have campaign document contains _id of document , importdata array. importdata array of objects containing unique date , source value.

my goal have object updated unique date/source pair. have new object replace matching object. in example below, fred may have donated tv, want application update object reflect donated both tv , radio.

// events (sample document) {   "_id" : "junky joe's jubilee",   "importdata" : [     {       "date": "2015-05-31",       "source": "fred",       "items": [         {item: "tv", value: 20.00},         {item: "radio", value: 5.34}       ]     },     {       "date": "2015-05-31",       "source": "mary",       "items": [         {item: "dresser", value: 225.00}       ]     }   ] } 

my original thought code below, not updating importdata fred's donations, i'm blowing away else in importdata array:

var collection = db.collection("events"); collection.update(   {_id: "junky joe's jubilee",     importdata: {       date: "2015-05-31",       source: 'fred'     },             },  // see if can find campaign object name   {     $set:       {"importdata":          {           date: "2015-05-31",           source: 'fred',           items: [             {item: "tv", value: 20.00},             {item: "radio", value: 5.34}           ]         }       }   },   {upsert: true});  // create document if 1 not exist campaign 

when tried pushing (instead of $set), getting multiple entries date/source combos (e.g. fred appear have donated 2 items multiple times on "2015-05-31").

how go doing mongodb native driver , nodejs?

try this

var collection = db.collection("events"); collection.update(   {_id: "junky joe's jubilee",     importdata: {       date: "2015-05-31",       source: 'fred'     },             },  // see if can find campaign object name   {     $set:       {"importdata.$":          {           date: "2015-05-31",           source: 'fred',           items: [             {item: "tv", value: 20.00},             {item: "radio", value: 5.34}           ]         }       }   },   {upsert: true});  // create document if 1 not exist campaign 

according documentation under array update operators should modify first element in array, matches query.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -