与承诺和推进的Firestore

问题描述 投票:-1回答:2

感谢Frank在Firebase为helping me with this code。我刚刚在Friends集合下推送文档ID时遇到了这个问题。我不确定在下面的代码中将const friendIdconst accepted推送到friendsList数组的最佳方法是什么。

const db = admin.firestore();
const friendRef = 
db.collection('users').doc(id).collection('friends');

friendRef.get().then((onSnapshot) => {
  var promises = [];

  onSnapshot.forEach((friend) => {
    const personId = String(friend.data().person_id);
    const friendId = String(friend.id);
    const accepted = friend.data().accepted;

    promises.push(db.collection('users').doc(personId).get());
  });

  Promise.all(promises).then((snapshots) => {
    friendsList = [];
    snapshots.forEach((result) => {
      friendsList.push({
        friendId: friendId,
        accepted: accepted,
        firstName: result.data().name.first,
        lastName: result.data().name.last,
      });
    });
    res.send(friendsList);
  });
}).catch((e) => {
  res.send({
    'error': e
  });
})

我尝试了一些东西,但它没有用。任何帮助,将不胜感激。

javascript firebase google-cloud-functions google-cloud-firestore
2个回答
3
投票

问题是你推入promises数组,你从每个db.collection('users').doc(personId).get()值的调用friend得到的。除了作为局部变量之外,你永远不会为每个朋友保留personIdfriendIdaccepted的值。

你应该把它们放在每一个承诺中。为此,您可以像这样返回自定义Promise。

promises.push(new Promise((resolve, reject) => {
    db.collection('users').doc(personId).get()
    .then(docResult => {
        resolve({         
            friendId: friendId,
            accepted: accepted,
            doc: docResult
        });
    })
    .catch(reason => {
        reject(reason);
    });
});

然后当你迭代快照数组时:

snapshots.forEach((result) => {
    friendsList.push({
        friendId: result.friendId,
        accepted: result.accepted,
        firstName: result.doc.data().name.first,
        lastName: result.doc.data().name.last,
    });
});

0
投票

正如我刚刚回答你对原始问题的回答一样,我的代码中出现了一个拼写错误的变量名称。

const db = admin.firestore();
const friendRef = db.collection('users').doc(id).collection('friends');

friendRef.get().then((friendsSnapshot) => {
  var promises = [];

  friendsSnapshot.forEach((friend) => {
    const friendId = String(friend.data().person_id);    
    promises.push(db.collection('users').doc(friendId).get());
  });

  Promise.all(promises).then((friendDocs) => {
    friendsList = [];
    friendDocs.forEach((friendDoc) => {
      friendsList.push({
        personId: friendDoc.id,
        firstName: friendDoc.data().name.first,
        lastName: friendDoc.data().name.last,
      });
    });
    res.send(friendsList);
  });
}).catch((e) => {
  res.send({
    'error': e
  });
})

因为你用doc(friendId)查找朋友的数据,所以friendDoc.id回调中的then()将是每个朋友的ID。

在这种情况下,我强烈建议保留Cloud Firestore参考文档。例如,在这种情况下,我发现DocumentSnapshot.id做了所需的事情。

© www.soinside.com 2019 - 2024. All rights reserved.