如何在文档内部的数组中获取DocumentReferences



云函数中的等待/异步模式非常新颖。拥有一个从具有DocumentReferences 数组的doucment获取数据的云函数

/* Create  new Chilla for a given date  */
exports.createNewSalikChilla = functions.https.onRequest(async (req, res) => {
const email=req.body.email;
const date=req.body.date;
console.log('Creating chilla for  Salik <' + email + '> on <' + date + '>');
const db = admin.firestore();
const habits = [];
const salikRef = db.collection('saliks').doc(email);
const salik = await salikRef.get();
if (!salik.exists) {
throw new Error("Salik not found for <" + email + ">");
}
const assignedHabits = salik.data()['assigned_habits'];
assignedHabits.forEach(element => { 
//LOST on how to get these Document Reference and push to habits = []
});
res.send({status: "Success"});
});

萨利克斯收藏的文件在消防仓库上具有以下结构

assigned_habits<array>:
0:
habit<reference>: /habits/first
required<number>: 200
1:
habit<reference>: /habits/second
required<number>: 4
name: "Hani Q"

但我已经尝试了所有的方法,似乎不知道如何在这里使用async/await来从数组中获取所有的DocumementRefrecence并推送到Habit array,然后在所有操作完成后,我发送回res.send({status:"Success"}(;

回答

以下是在实施接受答案后工作的

const assignedHabits = salik.data()['assigned_habits'];
const habits_data = (await Promise.all(assignedHabits.map(element => element.habit.get())))
.map(snapshot => snapshot.data());
console.log(habits_data);
res.send({status: habits_data});

每当需要等待一堆异步操作时,都需要使用Promise.all()。在你的情况下,这看起来像:

const assignedHabits = salik.data()['assigned_habits'];
const habits = await Promise.all(assignedHabits.map(element => element.habit.get()));
res.send({status: "Success"});

上面的代码假定habitDocumentReference字段类型。

相关内容

  • 没有找到相关文章

最新更新