简体   繁体   中英

How to add multiple map objects (JSON's) to cloud-firestore database?

I've a function that set one JSON to my Cloud Firestore database:

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

To invoke this function, I pass JSON body to POST request:

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

{
    "id": 45,
    "name": "Stack",
    "email": "stack@overflow.com",
    "phone_number": "+48 111 222 333"
}

Everything work fine, this request set this JSON as a map with id as a key, and values as a name , email and phone_number . But I want to pass several JSON's on one request to add several map objects to my NoSQL document, like:

[
    {
        "id": 45,
        "name": "Stack",
        "email": "stack@overflow.com",
        "phone_number": "+48 111 222 333"
    },
    {
        "id": 46,
        "name": "Stack2",
        "email": "stack2@overflow.com",
        "phone_number": "+48 222 222 333"
    },
    {
        "id": 47,
        "name": "Stack3",
        "email": "stack3@overflow.com",
        "phone_number": "+48 333 222 333"
    }
]

How to modify my firebase function to achieve this?

Since you have an array of objects, you'll need to loop over that array, and then create a document for each object. And since you need to wait until all documents are created, you can use Promise.all() .

Something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM