【问题标题】:Concatenating variables in a mongodb update query [duplicate]在mongodb更新查询中连接变量[重复]
【发布时间】:2016-05-16 04:43:32
【问题描述】:

我正在尝试使用 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() 方法工作,但我无法找到或适应这种特定情况。

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

【问题讨论】:

  • @BlakesSeven,你是对的!谢谢! :)
  • 这就是为什么向您显示横幅以确认链接的“问题/答案”对您有帮助的原因。这是一个常见的 JavaScript 符号错误。

标签: node.js mongodb express mongoskin


【解决方案1】:

试试这个:

    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);
    }
  );

【讨论】:

  • 不。 JavaScript“字符串化”键,因此更新语句将被视为表示"$set": { "field": req.body.nom },而不是将变量内容插入到对象中。
猜你喜欢
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多