2

I want to update any index of FirstCol array dynamically in Nodejs. How do I go about doing that in this collection.

   {
     "TableId": "0",
     "FirstCol": [
        "Have high energy ",
        "Talk more than listen "
     ]
    }

I know I can update a specific array index using the dot operator. For eg:

 db.testcol.update(
    { "TableId": "0" },
    { $set:
      {
        "FirstCol.1": "rain gear"
      }
     }
    )

But what if I did not know that I have to edit index 1 of array FirstCol. How to frame the update query in order to update the index of the array which is suppose in variable 'editIndex'. Can I do something like:

db.testcol.update(
        { "TableId": "0" },
        { $set:
          {
            "FirstCol.editIndex": "rain gear"
          }
         }
        )

Need your help. Thanks :)

1
  • This works db.arr.update({},{ $set: { "arr.0" : 'Your updated text' } }, {many:false}) Commented Oct 8, 2018 at 12:16

1 Answer 1

4

You can try with ES6 Computed Property Keys method

db.testcol.update(
  { "TableId": "0" },
  { "$set": {
    ["FirstCol." + editIndex]: "rain gear"
  }},
  function(err, res) {
    console.log(err)
    console.log(res)
  }
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response @Anthony I tried to execute the update query with a callback function like this: db.testcol.update( { "TableId": "0" }, { "$set": { ["FirstCol." + editIndex]: "rain gear" }} ),function(err,res) { if(err) console.log("QUERY was not Successfully") else{ console.log("QUERY Successfully"); res.send('Edited'); } } The control is not going to the callback function at all.
Upddated the answer
Thank-you so much @Anthony. This worked. I've marked your answer correct also.

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.