如何向云存储数据库添加多个地图对象(JSON)?

问题描述 投票:0回答:1

我有一个将一个JSON设置到我的Cloud Firestore数据库的函数:

app.post('/api/add/collection/:collection_id/permission/:permission_id', (req, res) => {
(async () => {
    try {
        await db.collection(req.params.collection_id)
            .doc(req.params.permission_id)
            .set({
                [req.body.id]: {
                    name: req.body.name,
                    email: req.body.email,
                    phone_number: req.body.phone_number
                }
            }, { merge: true}
            );

        return res.status(200).send('OK');
    } catch (error) {
        console.log(error);
        return res.status(500).send('ERROR' + error);
    }
})();
});

要调用此功能,我将JSON正文传递给POST请求:

https://.../app/api/add/collection/USER_ID/permission/PERMISSION_id

{
    "id": 45,
    "name": "Stack",
    "email": "[email protected]",
    "phone_number": "+48 111 222 333"
}

一切正常,该请求将此JSON设置为一个映射,以id为键,其值分别为nameemailphone_number。但是我想在一个请求中传递几个JSON,以将多个地图对象添加到我的NoSQL文档中,例如:

[
    {
        "id": 45,
        "name": "Stack",
        "email": "[email protected]",
        "phone_number": "+48 111 222 333"
    },
    {
        "id": 46,
        "name": "Stack2",
        "email": "[email protected]",
        "phone_number": "+48 222 222 333"
    },
    {
        "id": 47,
        "name": "Stack3",
        "email": "[email protected]",
        "phone_number": "+48 333 222 333"
    }
]

如何修改我的firebase函数以实现此目的?

javascript firebase express google-cloud-firestore http-post
1个回答
0
投票

由于具有对象数组,因此需要遍历该数组,然后为每个对象创建一个文档。而且由于您需要等到所有文档创建完毕后,才可以使用Promise.all()

类似这样的东西:

try {
    await Promise.all(req.body.map((object) => {
        return db.collection(req.params.collection_id)
          .doc(req.params.permission_id)
          .set({
            [object.id]: {
                name: object.name,
                email: object.email,
                phone_number: object.phone_number
            }
          }, { merge: true});
    });
    return res.status(200).send('OK');
} catch (error) {
    console.log(error);
    return res.status(500).send('ERROR' + error);
}
© www.soinside.com 2019 - 2024. All rights reserved.