当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Nodejs + mongodb + dynamic $set without declaring a variable

问题描述:

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

网友答案:

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 })
      }
    }
)
分享给朋友:
您可能感兴趣的文章:
随机阅读: