Firebase:从JSON在集合中设置多个文档-自动添加UserID

mspsb9vt  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(156)

所以我有以下内容:

FoodSample.forEach((doc) => {
firebaseConfig.firestore().collection("customers").doc().set(doc);
})

FoodSample是我的JSON文件,看起来像:

[{
    "Category": "BREAKFAST",
    "Name": "Bacon",
    "Weight": "0.4"
},
{
    "Category": "BREAKFAST",
    "Name": "Eggs",
    "Weight": "0.1"
}]

这样做很好,但是在集合中,我还想将userID作为字段添加到每个记录(id.user.uid)上--我如何在集合(doc)中设置这个字段,或者如何将它添加到JSON中。我无法手动将其添加到JSON中,因为每个用户在注册时都是不同的。
编辑:
我可以这样做:

const res = {
...FoodSample,
message: FoodSample.map(el => ({
...el,
User: id.user.uid,
}))
}

然后我可以使用这个res作为我的数组-但我不希望'message'中的数组-只是修改现有的数组?

jv2fixgn

jv2fixgn1#

我建议在并行执行对异步方法的不同调用时使用Promise.all()
如果我正确理解你的问题,下面的方法可以做到这一点:

const promises = [];

FoodSample.forEach(obj => {
    obj.user = id.user.uid;
    promises.push(firebaseConfig.firestore().collection("customers").add(obj));
});

return Promise.all(promises);

请注意,add({...})doc().set({...})相同。

相关问题