0

Image

I have been using this method to update the object dynamically, is there any way I can do this without setting up a variable like I do with query?

This is what I am currently using:

var query = {}
query["settings.panels."+req.params.type+"."+req.params.id] = req.body

mongoPool.collection('settings').updateOne(
    {_id: req.user.profile.id},
    { 
      $set: query,
    (err, doc) => {
    if (!err) {
      res.status(200).send({ errorStatus: false, returnData: doc }
    } else {
    console.log(err);
    res.status(200).send({ errorStatus: true, errorMsg: 'Db Error',   errorCode: 405 })
    }
})

This is what I want:

mongoPool.collection('settings').updateOne(
    {_id: req.user.profile.id},
    { 
      //notice I didnt use query & this returns an array
      $set: ["settings.panels."+req.params.type+"."+req.params.id] : req.body
    }, (err, doc) => {
    if (!err) {
      res.status(200).send({ errorStatus: false, returnData: doc }
    } else {
    console.log(err);
    res.status(200).send({ errorStatus: true, errorMsg: 'Db Error',   errorCode: 405 })
    }
})

Instead it returns an array

1
  • 1
    No, that is not possible. Commented Nov 15, 2015 at 13:28

1 Answer 1

2

As long as you're using Node.js 4.x or above, you can use its ES6 support for computed property names to do this:

mongoPool.collection('settings').updateOne(
    {_id: req.user.profile.id},
    { 
      $set: { ["settings.panels."+req.params.type+"."+req.params.id]: req.body }
    },
    (err, doc) => {
      if (!err) {
        res.status(200).send({ errorStatus: false, returnData: doc }
      } else {
        console.log(err);
        res.status(200).send({ errorStatus: true, errorMsg: 'Db Error',   errorCode: 405 })
      }
    }
)
Sign up to request clarification or add additional context in comments.

Comments

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.