在mongodb更新查询中连接变量

时间:2016-02-06 03:51:01

标签: node.js mongodb express mongoskin

我正在尝试使用Mongodb更新数组中的特定字段。为此,我正在尝试使用以下代码:

  db.collection(CG).update(
    { 
      _id : ObjectId(req.params.id) 
    },
    { 
      $set: { "cg." + req.params.index + ".nom" : req.body.nom } 
    }, 
    function (err, result){
        res.json(result);
    }
  );

但是,这种方法不会运行。问题出现了这个问题:

$set: { "cg." + req.params.index + ".nom" : req.body.nom }

如果我更改此行:

$set: { "cg.0.nom" : req.body.nom }

它运行。

注意到...在这行中我正在访问具有以下结构的'cg'元素:

据我所知,有一些解决方案(使用投影)适用于.find()方法,但我无法找到或适应这种特定情况。

欢迎任何提示/建议/新解决方案,谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

    var field = "cg." + req.params.index + ".nom"

    db.collection(CG).update(
    { 
      _id : ObjectId(req.params.id) 
    },
    { 
      $set: { field : req.body.nom } 
    }, 
    function (err, result){
        res.json(result);
    }
  );