Firestore: What is the best way to populate array of ids with its content?

时间秒杀一切 提交于 2021-02-07 09:57:56

问题


I have array of objects containing users Ids.

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

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 ?

This is my current 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()));
            })

回答1:


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.

See source code below.

// 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']))


来源:https://stackoverflow.com/questions/47608271/firestore-what-is-the-best-way-to-populate-array-of-ids-with-its-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!