[英]Trouble batch setting a document field by docId in Firestore
I have been using firebase (firestore) for a while but I'm a little stuck and was wondering if anyone can think of a solution.我一直在使用 firebase (firestore) 一段时间,但我有点卡住了,想知道是否有人能想到一个解决方案。
On the firestore DB I have a single collection of users, each user has an email address and several other fields.在 Firestore DB 上,我有一个用户集合,每个用户都有一个 email 地址和其他几个字段。 In this instance I am checking if a user email exists and if it does, I want to create a list field for that particular user with a listUid.
在这种情况下,我正在检查用户 email 是否存在,如果存在,我想使用 listUid 为该特定用户创建一个列表字段。 I am referencing the users by email, grabbing the docId for those users and then trying to set a list field for each of them.
我通过 email 引用用户,获取这些用户的 docId,然后尝试为每个用户设置一个列表字段。
I am not getting any error's from firestore, it's simply not updating in the DB for some reason and I can't figure out where I am going wrong.我没有从firestore收到任何错误,它只是由于某种原因没有在数据库中更新,我不知道我哪里出错了。 Thanks in advance
提前致谢
export const addListUidToExistingUserList = (
{ firestore },
emailArray,
listUid
) => {
return async () => {
let docIds = [];
emailArray.forEach((emailAddress) => {
//find users by email (works)
const query = db
.collection("users")
.where("email", "==", emailAddress);
//get docId's for user with matching email (works)
query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docIds.push(doc.id);
});
});
//add a new list with corresponding listUid (does not work)
docIds.forEach((id) => {
let userRef = db.collection("users").doc(id);
batch.set(userRef, { lists: [{ listUid }] });
});
});
return await batch.commit();
};
};
You are running into this issue because your docIds
array is always empty at the time you call docIds.forEach
.您遇到此问题是因为您的
docIds
数组在您调用docIds.forEach
时始终为空。
That's because query.get().then
runs asynchronously, and so docIds.forEach
is not waiting for it to complete.那是因为
query.get().then
异步运行,所以docIds.forEach
不会等待它完成。
You could either:您可以:
await query.get().then
; await query.get().then
; ordocIds.forEach
function INSIDE the then
callback of query.get
.then
回调中添加docIds.forEach
query.get
。 Here are your possible fixes:以下是您可能的修复:
await query.get().then
//get docId's for user with matching email (works)
await query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docIds.push(doc.id);
});
});
OR:或者:
docIds.forEach
inside then
docIds.forEach
里面then
//get docId's for user with matching email (works)
query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docIds.push(doc.id);
});
docIds.forEach((id) => {
let userRef = db.collection("users").doc(id);
batch.set(userRef, { lists: [{ listUid }] });
});
});
Note: Of course, you could also add
batch.set
directly into your first iteration ofquerySnapshot.docs.forEach
to prevent an unnecessary iteration.注意:当然,您也可以将
batch.set
直接添加到querySnapshot.docs.forEach
的第一次迭代中,以防止不必要的迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.