【问题标题】:JavaScript/Typescript Declaring Object with Quoted Key for MongoDB '$push' PropertyJavaScript/Typescript 为 MongoDB '$push' 属性声明带引号的键的对象
【发布时间】:2018-07-17 09:06:37
【问题描述】:

我正在尝试准备数据以将元素添加到 MongoDB 的嵌套数组中。我这样做是打字稿:

var data = {$push:{"foo.12.bar":{
    prop1: prop1,
    prop2: prop2,        // the right hand side values identified above the code
         ...
}}};

当我写这个“foo.12.bar”时,它工作得很好。但我想要做的是把这个“foo.12.bar”值放在一个变量中,让它可变。

这不起作用:

var propString = "foo.12.bar";

var data = {$push:{propString:{
    prop1: prop1,
    prop2: prop2,        // the right hand side values identified above the code
         ...
}}};

我不能在 $push 属性之后写任何变量名。我该如何解决?

【问题讨论】:

  • 使用[propString]
  • @SurenSrapyan 效果很好,非常感谢

标签: javascript json node.js mongodb typescript


【解决方案1】:

你必须使用括号表示法。

var propString = "foo.12.bar";

var data = {$push:{}};

data[propString] = {
    prop1: prop1,
    prop2: prop2
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2011-01-13
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多