1

I'm using mongoose and I'm doing an update of my db by using findByIdAndUpdate() function. I'd like to push elements into different arrays present in my document. I have in my document different array with different names. May I pass as parameter the name array to this function or I should create different function where every function has a different nameArray?

  this.findByIdAndUpdate(User._id,
                        {$push:{nameArray: 'element'}}, 
                        {upsert: true},
                        callback);
Mazzy
  • 13,354
  • 43
  • 126
  • 207
  • JavaScript Object literals don't currently allow variables as keys. An identifier on left of the `:` will be taken for its name, so `"nameArray"` is the name of the property. Related: [How do I add a property to a Javascript Object using a variable as the name?](http://stackoverflow.com/questions/695050) and related to [Is this Javascript object literal key restriction strictly due to parsing?](http://stackoverflow.com/questions/2873163) – Jonathan Lonowski Aug 24 '14 at 19:40
  • 1
    Though, for future reference, current ECMAScript 6 drafts have defined a *ComputedPropertyName* syntax for Object initializers -- `{ [nameArray]: 'element' }`. – Jonathan Lonowski Aug 24 '14 at 19:42

1 Answers1

3

In Node.js 4.x you can use the computed property syntax to do this directly in the $push object literal:

this.findByIdAndUpdate(User._id,
                       {$push: {[nameArray]: 'element'}}, 
                       {upsert: true},
                       callback);

In previous versions, you need to build your $push object programmatically:

var push = {};
push[nameArray] = 'element';
this.findByIdAndUpdate(User._id,
                       {$push: push}, 
                       {upsert: true},
                       callback);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471