Firebase Firestore,如何有效地从对象数组中更新多个集合



我有这个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"很多次了。

是否有一个更好的选择来更新多个集合从数组的对象?

这太浪费了:

db.collection("category")
.get()
.then((snapshot) => {
snapshot.forEach((docRef) => {
let name = "My Category";
if (docRef.data().name === name) {
...

您正在从category检索所有文档,然后仅处理以"My Category"作为其名称的文档。如果存在具有其他名称的文档,则应该使用查询只检索需要处理的文档:

db.collection("category")
.where("name", "==", "My Category")
.get()
.then((snapshot) => {
snapshot.forEach((docRef) => {
...

可能还有更多的事情,但这是第一个让我眼前一亮的。

这项工作可以在服务器端通过云功能onWrite触发监听Categories集合来完成。

还要考虑更有效地构建数据,是否可以将子类别存储在父类别中,以便确切地知道哪些文档需要更新?

最新更新