【问题标题】:How do you pass the value of a variable to a firebase call?如何将变量的值传递给 firebase 调用?
【发布时间】:2020-01-23 15:30:43
【问题描述】:

复制自 firebase 文档:

// Create an initial document to update.
var frankDocRef = db.collection("users").doc("frank");
frankDocRef.set({
    name: "Frank",
    favorites: { food: "Pizza", color: "Blue", subject: "recess" },
    age: 12
});

// To update age and favorite color:
db.collection("users").doc("frank").update({
    "age": 13,
    "favorites.color": "Red"
})
.then(function() {
    console.log("Document successfully updated!");
});

我希望能够做到:

const var1 = 'color'
const color = 'red'
db.collection("users").doc("frank").update({
    "age": 13,
    "favorites.$var1$": color
})

其中$var1$ 指的是$var1$ 持有的值,在这种情况下是食物、颜色或主题。

在这种情况下,括号表示法不起作用,因为我将一个字符串传递给 firebase,它不会这样解释。

预先构建字符串,如:

const aString = 'favorites.' + var1 

也不起作用,因为您不能像这样传递变量aString

db.collection("users").doc("frank").update({
    "age": 13,
    aString: "Red"
})

有办法吗?

【问题讨论】:

    标签: javascript arrays firebase


    【解决方案1】:

    使用方括号[]:

    db.collection("users").doc("frank").update({
        "age": 13,
        [aString]: "Red"
    })
    

    欲了解更多信息,请参阅MDN - Computed property names

    【讨论】:

      猜你喜欢
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 2011-11-13
      相关资源
      最近更新 更多