cari

Rumah  >  Soal Jawab  >  teks badan

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

下面语句可以执行成功:

1

2

<code>Basket.update({"pname":pname}

         ,{"$set":{"pprice.1.2":123}});</code>

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

1

2

<code>Basket.update({"pname":pname}

         ,{"$set":{eprice:123}});</code>

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

1

2

3

4

5

6

7

<code>{ [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.' }</code>

下面语句执行成功:

1

<code>"$set":{[`pprice.${emonth}.${eday}`]:pprice}</code>

PHPzPHPz2898 hari yang lalu288

membalas semua(2)saya akan balas

  • 阿神

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

    1

    <code>{$set:{[`OuterKey.${theUncertainInnerKey}`]:theValue}}</code>

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

    balas
    0
  • 巴扎黑

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

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

    balas
    0
  • Batalbalas