Firestore:用其内容填充ID数组的最佳方法是什么? [英] Firestore: What is the best way to populate array of ids with its content?

查看:37
本文介绍了Firestore:用其内容填充ID数组的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含用户ID的对象数组.

I have array of objects containing users Ids.

const userIDs= [{key: 'user_1'},{key: 'user_2'}, {key: 'user_3'}];

我想用Cloud Firestore中的用户数据填充它.

I want to fill it with user data from cloud firestore.

const userIDs= [
{key: 'user_1', name: 'name1'},
{key: 'user_2', name: 'name2'}, 
{key: 'user_3', name: 'name3'}
];

最快,最便宜的方法是什么?

What is the fastest and less pricey way of doing it ?

这是我目前的做法.

      const filledUsers = [];
            for (let index in userIDs) {
                const user = Object.assign({}, concatUsers[index]);
                const snapshot = await usersRef.doc(user.key).get();
                filledUsers.push(Object.assign(user, snapshot.data()));
            })

推荐答案

在for循环内使用 await 效率低下.相反,最好在执行的 ref.get()列表上使用 Promise.all ,然后在 await 上使用.

Use await inside the for loop is inefficient. Instead, it's best to use Promise.all on list of executed ref.get() and then await.

如果需要降低价格,则需要应用缓存.

If you need to reduce the price, you need to apply caching.

请参见下面的源代码.

// module 'db/users.js'

const usersRef = db.collection('users');

export const getUsers = async (ids = []) => {
    let users = {};

    try {
        users = (await Promise.all(ids.map(id => usersRef.doc(id).get())))
            .filter(doc => doc.exists)
            .map(doc => ({ [doc.id]: doc.data() }))
            .reduce((acc, val) => ({ ...acc, ...val }), {});

    } catch (error) {
        console.log(`received an error in getUsers method in module \`db/users\`:`, error);
        return {};

    }

    return users;
}

// Usage:
//
// (await getUsers(['user_1', 'user_2', 'user_3']))

这篇关于Firestore:用其内容填充ID数组的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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