问题
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