【问题标题】:How to write to Firestore document from Firebase Cloud Function?如何从 Firebase Cloud Function 写入 Firestore 文档?
【发布时间】:2020-07-30 10:42:26
【问题描述】:

我正在尝试制作云功能。 每当我尝试到达终点时,我都会得到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);
});

这是我从 Postman 发送的 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)

【问题讨论】:

  • 请不要将错误描述添加为图像。直接添加文字。

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


【解决方案1】:

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

另外,请考虑按照Firebase guidelines 重构您的代码以处理 POST 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2021-11-25
    • 2018-06-22
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多