带有承诺和推送的 Firestore [英] Firestore with promises and push

查看:14
本文介绍了带有承诺和推送的 Firestore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢 Firebase 的 Frank 帮助我编写此代码.我只是在将文档 ID 推送到 Friends 集合下时遇到了这个问题.我不确定在下面的代码中将 const friendIdconst accepted 推送到 friendsList 数组的最佳方法是什么.

Thanks to Frank over at Firebase for helping me with this code. I just had this one issue with pushing the document id under Friends collection. I am not sure what is the best way to push const friendId and const accepted to friendsList array in the code below.

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
  });
})

我尝试了一些方法,但没有成功.任何帮助将不胜感激.

I tried a few things, but it didn't work. Any help would be appreciated.

推荐答案

问题是你将调用 db.collection('users').doc(personId).get() 用于每个 friend 值.你永远不会为每个朋友保留 personIdfriendIdaccepted 的值,除非作为局部变量.

The problem is that you push in the promises array what you get from the calls db.collection('users').doc(personId).get() for each friend value. And you never keep values of personId, friendId, accepted for each friend except as local variables.

你应该把它们放在每一个 promise 数组中.为此,您可以像这样返回自定义 Promise.

You should keep them in every array of promises. For this you can return custom Promise like this.

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);
    });
});

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

and then when you iterate snapshots array:

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

这篇关于带有承诺和推送的 Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆