Mow*_*zer 5 firebase reactjs google-cloud-firestore
我想使用点表示法更新 Cloud Firestore 中嵌套对象中的字段。但点符号引用的那些字段是变量。
我怎样才能做到这一点?
文档// To update age and favorite color:
db.collection("users").doc("frank").update({
"age": 13,
"favorites.color": "Red"
})
Run Code Online (Sandbox Code Playgroud)
但是如果我需要创建favorites.color
一个变量怎么办?
const attributes = [ 'jobs', 'schools', 'favorites', ];
const values = [ 'food', 'song', 'color', ];
const variableData = [attributes[2]].[values[2]]; // 'favorites.color'
Run Code Online (Sandbox Code Playgroud)
我可不可以做:
db.collection("users").doc("frank").update({
"age": 13,
"[attributes[2]].[values[2]]": "Red"
})
Run Code Online (Sandbox Code Playgroud)
确切地说,这会如何运作?
编辑:
我试过:
db.collection("users").doc("frank").update({
"age": 13,
`${[attributes[2]]}.${[values[2]]}`: "Red"
})
Run Code Online (Sandbox Code Playgroud)
并得到以下错误:
解析错误:意外的标记
尝试时也会出现同样的错误
`"${[attributes[2]]}.${[values[2]]}"`: "Red"
Run Code Online (Sandbox Code Playgroud)
(认为 Firebase 需要引号来解析语法。)
您缺少的关键是,当您使用计算属性名称时,您需要将表达式包装在[]
. 例如,您应该将其写为以下形式:
db.collection("users").doc("frank").update({
"age": 13,
[`${attributes[2]}.${values[2]}`]: "Red"
})
Run Code Online (Sandbox Code Playgroud)
可运行示例:
db.collection("users").doc("frank").update({
"age": 13,
[`${attributes[2]}.${values[2]}`]: "Red"
})
Run Code Online (Sandbox Code Playgroud)
注意:在 javascript 中写出键时,引号并不重要。我们在这里只使用反引号,因为我们希望每个值(“最喜欢的”、“颜色”)通过点连接在一起。
归档时间: |
|
查看次数: |
2207 次 |
最近记录: |