【发布时间】:2022-11-24 23:52:38
【问题描述】:
我有这个 firestore 集合需要根据对象数组中的数据进行更新,起初这不是问题。但随着数据的增长。将数据更新到 firebase 是我们必须比较每个 id,然后对所有数据执行更新。
这里我有一些数组,
let newCategoriesUpdate = [
{
category_id: 100001,
parent_category_id: 0,
name: "Health",
isActive: true,
has_children: true,
},
{
category_id: 100019,
parent_category_id: 100001,
name: "Medical Equipment",
isActive: true,
has_children: false,
},
{
category_id: 100020,
parent_category_id: 100001,
name: "Laboratory",
isActive: false,
has_children: false,
},
]
该列表包含 200 多个对象,需要在每个循环中进行比较,这需要更多的时间和内存。
这是我在 firebase 中实现的,用于从上面的对象数组更新集合
const handleUpdateCategories = () => {
db.collection("category")
.get()
.then((snapshot) => {
snapshot.forEach((docRef) => {
let name = "My Category";
if (docRef.data().name === name) {
let categoryRef = docRef.id;
db.collection("category")
.doc(categoryRef)
.collection("categoryList")
.get()
.then((snapshotCollection) => {
// loop collection from firebase
snapshotCollection.forEach((catListDocRef) => {
let categoryListRefId = catListDocRef.id;
// need to compare each loop in array
// loop array to update
newCategoriesUpdate.map((category) => {
if (
catListDocRef.data().categoryId === category.category_id
) {
db.collection("category")
.doc(categoryRef)
.collection("categoryList")
.doc(categoryListRefId)
.set(
{
categoryId: category.category_id,
isActive: category.isActive,
categoryName: category.name,
},
{ merge: true }
)
.then(() => {
console.log("UPDATE Success");
})
.catch((err) => {
console.log("ERR", err);
});
}
});
});
});
}
});
});
};
此方法有效,并且在控制台中也多次显示消息“UPDATE Success”。
有没有更好的选择来更新对象数组的多个集合?
【问题讨论】:
-
batch.commit()?
标签: javascript firebase google-cloud-firestore