nmac
nmac

Reputation: 680

dynamically name mongo key field

I want to name a mongo key dynamically based on a variable. For instance,

MyCollection.update({_id: id}, 
{ 
  $set: 
   {
     getsNamedDynamically: { 
        //stuff
     }...

I would like to set the value of getsNamedDynamically in a variable to assign a different key name to the field based on some other factors. I've tried doing this, however, mongo takes the value literally (i.e. as a string) and does not bother to find the variable's value in the program.

Upvotes: 0

Views: 2609

Answers (2)

Vishal Patel
Vishal Patel

Reputation: 1745

You can set it dynamically, if you are using node v4, you can use the ES6 enhanced literal syntax:

MyCollection.update({_id: id}, 
{ 
  $set: {[key] : value}
}

Upvotes: 1

Marius Darila
Marius Darila

Reputation: 873

Did you tried this aproach?(dont know if it works)

var dataToSet={};
dataToSet['field']= "some computed value";

and then

MyCollection.update({_id: id}, 
{ 
  $set: dataToSet
}

Upvotes: 1

Related Questions