search

Home  >  Q&A  >  body text

javascript - MongoDB更新语句中如何引用变量?

下面语句可以执行成功:

Basket.update({"pname":pname}
         ,{"$set":{"pprice.1.2":123}});

但是"pprice.1.2"中,"1.2"需要是变量的值,1取emonth的值,2取eday的值。
我创建新的变量,eprice="pprice."+emonth+"."+eday;
但是下面语句执行后没效果:

Basket.update({"pname":pname}
         ,{"$set":{eprice:123}});

目前是没有"pprice"这个键的。
修改为"pprice.${emonth}.${eday}",出现下面错误:

{ [MongoError: The dollar ($) prefixed field '${eday}' in 'pprice.${emonth}.${eday}' is not valid for storage.]
  name: 'MongoError',
  message: 'The dollar ($) prefixed field \'${eday}\' in \'pprice.${emonth}.${eday}\' is not valid for storage.',
  driver: true,
  index: 0,
  code: 52,
  errmsg: 'The dollar ($) prefixed field \'${eday}\' in \'pprice.${emonth}.${eday}\' is not valid for storage.' }

下面语句执行成功:

"$set":{[`pprice.${emonth}.${eday}`]:pprice}
PHPzPHPz2897 days ago278

reply all(2)I'll reply

  • 阿神

    阿神2017-04-10 17:16:20

    {$set:{[`OuterKey.${theUncertainInnerKey}`]:theValue}}

    需要使用ES6,babel网站上原文好像被删了……参考这篇译文吧结合 ES6+ 开发 React 组件
    补充一下格式,不要打错了:
    左方括号,反引号,(可能需要的额外字符串),美元符号,左大括号,加上变量,右大括号,(可能需要的额外字符串),反引号,右方括号

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 17:16:20

    我说个土办法,可以先find,然后在save,find后的document是可以直接修改完save的

    reply
    0
  • Cancelreply