如何从Firebase Cloud Function写入Firestore文档?

时间:2020-07-30 10:42:26

标签: firebase google-cloud-firestore google-cloud-functions firebase-admin

我正在尝试使云功能。 每当我尝试到达终点时,我都会得到500 Internal Server Error Postman Response Image here

我检查了Firebase功能的日志,也没有看到任何信息。 它只是说“功能崩溃”,没有任何更多信息。

我还检查了Firestore数据库结构中是否有拼写错误和不匹配,但对我来说一切正常。

这是我在Firebase项目上上传的Firebase功能代码。


const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { error } = require('firebase-functions/lib/logger');
admin.initializeApp(functions.config().firebase);


exports.addEvent = functions.region('asia-east2').https.onRequest(async (req, res) => {
    if (req.method === 'POST') {

        var db = admin.firestore();
        var write = db.collection("Colleges")
        .doc(req.body.college)
        .collection("events")
        .doc(req.body.event.id)
        .set({
            id: req.body.event.id,
            admin: req.body.event.admin,
            event_state: req.body.event.event_state,
            name: req.body.event.name,
            poster_url: req.body.event.poster_url,
            start_date_time: req.body.event.start,
            end_date_time: req.body.event.end,
            location: req.body.event.location,
            short_desc: req.body.event.shortDesc,
            long_desc: req.body.event.longDesc,
            contacts: req.body.event.contacts,
            links: req.body.event.links,
        });
        return res.send(write);
    }
    else
        return res.sendStatus(403);
});

这是我从邮递员发送的POST请求的正文

{
    "college": "college_name",
    "event": {
        "id": 1234,
        "admin": "admin",
        "event_state": 2,
        "name": "Event Name",
        "poster_url": "test",
        "start": "Date Time",
        "end": "Date Time",
        "location": "auditorium",
        "shortDesc": "lorem ipsum short",
        "longDesc": "lorem ipsum long",
        "contatcs": [
            {
                "tag": "Name Tag",
                "contact": 12345678
            }
        ],
        "links": [
            {
                "tag": "Link Tag",
                "link": 123456784
            }
        ]
    }
}

Firestore结构类似

    -Colleges (Collection)
       |
       |
        -Document 
             |
              -events(Collection)
                  |
                   -Event Documents (Document which i want to write to ,from the firebase function)

1 个答案:

答案 0 :(得分:1)

问题是有效载荷中的事件ID是number,而Firestore文档ID必须是字符串。因此,您可以使用.doc(req.body.event.id.toString())或将事件ID作为字符串发送到有效负载id: "1234"中。

另外,考虑重构Firebase guidelines之后的代码以处理POST方法。