因此基于对象字段上的firestore documentation:
// 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!");
});
如何更新收藏夹字段的多个属性,例如
db.collection("users").doc("frank").update({
"age": 13,
"favorites.color": "Red",
"favorites.food": "Burger"
})
此操作在控制台中显示msg失败:
未处理的错误错误:参数“ dataOrField”无效 UpdateMap。多次指定“收藏夹”字段。
我也尝试过使用merge: true
选项,例如。
db.collection("users").doc("frank").update({
"age": 13,
"favorites": {
"color": "Red",
"food": "Burger"
}
}, {merge: true})
但这会覆盖整个收藏夹字段,这意味着'subject'属性消失了。
有什么想法吗?
这是我的实际代码:
“ cardId”来自POST请求中的body.cardId
return db.runTransaction(t => {
let user
let hasDefault = false
return t.get(userRef).then(userDoc => {
if (!userDoc.exists) throw new HttpsError('not-found', 'user-not-found')
user = userDoc.data()
if (!user.cards || !user.cards[cardId]) throw new HttpsError('not-found', 'card-not-found')
return updateCustomer(user.cid, { defaultCard: cardId })
}).then(customer => {
const prevDefaultId = Object.keys(user.cards).find(cardId => user.cards[cardId] && user.cards[cardId].default)
let userUpdateData = {}
if (prevDefaultId && prevDefaultId !== cardId) {
userUpdateData[`cards.${prevDefaultId}.default`] = false
}
userUpdateData[`cards.${cardId}.default`] = true
return t.update(userRef, userUpdateData, {merge: true})
})
})
我通过两次更新来解决它:
return db.runTransaction(t => {
let user
let hasDefault = false
return t.get(userRef).then(userDoc => {
if (!userDoc.exists) throw new HttpsError('not-found', 'user-not-found')
user = userDoc.data()
if (!user.cards || !user.cards[cardId]) throw new HttpsError('not-found', 'card-not-found')
return updateCustomer(user.cid, { defaultCard: cardId })
}).then(customer => {
const prevDefaultId = Object.keys(user.cards).find(cardId => user.cards[cardId] && user.cards[cardId].default)
if (prevDefaultId && prevDefaultId !== cardId) {
t.update(userRef, {
[`cards.${prevDefaultId}.default`]: false
}, {merge: true})
}
return t.update(userRef, {
[`cards.${cardId}.default`]: true
}, {merge: true})
})
})
答案 0 :(得分:2)
要在Firestore文档中update多个字段,您需要使用字段,值,字段,值...格式:
db.collection("users").doc("frank").update({
"age", 13, // field, value
"color, "red" // field, value
})
如果要更新嵌套字段,则有两个选择。
像您提到的那样使用点符号:
db.collection("users").doc("frank").update({
"age", 13,
"favorites.color", "Red",
"favorites.food", "Burger"
})
使您的“价值”成为地图:
db.collection("users").doc("frank").update({
"age", 13,
"favorites", mapOf(
"color" to "Red",
"food" to "Burger"
})