6

I'm trying to update an array in my collection with this:

 var str = "list.0.arr";
    db.collection('connect').update({_id: id}, {$push:  { `${str}`: item}}); 

This exact string works just fine if I do it like this:

db.collection('connect').update({_id: id}, {$push:  { "list.0.arr": item}}); 

This is to show that it works, but It's throwing an error Unexpected token when I use the first solution.

My question is, how can I get the top solution to work as the Object key?

2 Answers 2

6

Template literals cannot be used as key in an object literal. Use a computed property instead:

db.collection('connect').update({_id: id}, {$push: {[str]: item}}); 
//                                                  ^^^^^

See also Using a variable for a key in a JavaScript object literal

Sign up to request clarification or add additional context in comments.

2 Comments

This does not work. It gives: SyntaxError: Unexpected token [. I suspect mongo doesn't support this syntax. (Using version 2.6.11)
@hackel: That has nothing to do with MongoDB, rather with the Node version you are using. See node.green for which features are supported in each version.
2

Create the update document with the string as key prior to using it in the update:

var str = "list.0.arr",
    query = { "_id": id },
    update = { "$push": {} };
update["$push"][str] = item;
db.collection('connect').update(query, update); 

1 Comment

Thanks a lot, this worked for me after I was almost gave up , var Now = new Date(); var currMonth = Now.getMonth(); var currYear = Now.getFullYear(); console.log(currYear, currMonth); var query = {shareId: share}, inc = { "$inc": {} }; inc["$inc"][interactions.views.${currYear}.${currMonth}] = 1 ; ShareStat.findOneAndUpdate(query, inc);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.