【问题标题】:How to get DocumentReferences in array inside a Document如何在文档内的数组中获取文档引用
【发布时间】:2020-03-02 23:43:05
【问题描述】:

云函数中的等待/异步模式非常新。具有从具有 DocumentReferences 数组的文档中获取数据的云函数

/* 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"});
});

saliks 集合中的文档在 firestore 上具有以下结构

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

但是已经尝试了所有方法,但似乎无法弄清楚如何在这里使用 async/await 从数组中获取所有 DocumementReferecnce 并推送到 Habit Array,然后在完成后我发回 res.send({status : "成功"});

回答

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

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

【问题讨论】:

    标签: node.js google-cloud-firestore async-await google-cloud-functions


    【解决方案1】:

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

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

    以上代码假定habitDocumentReference 字段类型。

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多