reactjs - doc内数组中的firestore更新值
问题描述
我看了几个小时的 firestore 文档,仍然没有找到解决这个案例的方法。我需要添加一个 ammout 功能来生产我的电子商务应用程序。
数据结构:主要集合是“购物车”,文档是用户电子邮件。
这是添加或设置产品的当前代码:
import firebase from 'firebase';
export async function addToCart(userMail, itemId, name, url, price, category, type, description) {
const ammout = 1
const cartItem = { itemId, name, url, price, category, type, description, ammout }
if (userMail === undefined) throw console.error('please Login');
const userDoc = await firebase.firestore().collection("cart").doc(userMail)
await userDoc.get().then((doc) => {
if (doc.exists) {
(async () => {
await userDoc.update({
item: firebase.firestore.FieldValue.arrayUnion(cartItem),
})
})()
}
else {
(async () => {
await userDoc.set({
item: firebase.firestore.FieldValue.arrayUnion(cartItem)
})
})()
}
})
}
解决方案
问题可能是您在同一个函数中同时使用两者await
,Promise.then()
这可能会产生一些同步问题,您也不需要await
填充userDoc
变量,正如您在firestore 文档示例中看到的那样。
所以基本上我会async/await
从你的代码中删除所有这些,因为它们并不是真正需要的,并且Promise.then()
足以.get()
确保你的代码中的同步性,看起来像这样:
export function addToCart(userMail, itemId, name, url, price, category, type, description) {
const ammout = 1
const cartItem = { itemId, name, url, price, category, type, description, ammout }
if (userMail === undefined) throw console.error('please Login');
const userDoc = firebase.firestore().collection("cart").doc(userMail)
userDoc.get().then((doc) => {
if (doc.exists) {
userDoc.update({
item: firebase.firestore.FieldValue.arrayUnion(cartItem),
})
}
else {
userDoc.set({
item: firebase.firestore.FieldValue.arrayUnion(cartItem)
})
}
})
}
推荐阅读
- node.js - 从 API / MongoDB 检索用户集合但排除密码字段?
- default - 更改 BlueSky Statistics 中的默认输出样式
- alibaba-cloud - 如何监控我的阿里云 ECS 实例?
- python - 切换状态以在 Python 中使用按钮触发功能 - 虽然循环打开和关闭
- c++ - 如何在 Visual Studio 2017 社区版中编译字节币源
- go - 将 big.Int 转换为 little-endian 字节切片
- java - MergeSort 数组的右侧部分
- r - 将具有多行的一个变量转换为多列
- algorithm - 在半径增加的二维网格中查找相邻单元格
- r - 在小标题中将 NaN 转换为 NA