如何在文档Firebase Function Express上创建子集合?

时间:2019-11-26 10:33:14

标签: node.js firebase express google-cloud-firestore

下面的代码段是我如何在文档下为PostID创建likes的子集合的方法。我收到未找到404错误。我已经阅读了一个文档,如果在文档集下有文档,可以在其中创建文档集。

Post-> PostId->点赞

exports.updateLike = function (req, res) {

    const postId = req.params.postId;
    const userId = req.params.userId;

    // return 404 not found 
    db.collection("posts").doc(postId).collection("likes").add({
        uid: userId,
        createAt: Date.now()
    }).catch(err => { 
        console.log("--- Operation Failure ---")
        return res.status(500).json(err);
    });
}; 

是链接 of image the structure of collection and document of the firebase

更新 我在firebase的控制台上检查并返回

TypeError: db.collection(...).doc(...).collection(...).set is not a function
    at exports.updateLike (/srv/routes/posts.js:47:60)
    at Layer.handle [as handle_request] (/srv/node_modules/express/lib/router/layer.js:95:5)
    at next (/srv/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/srv/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/srv/node_modules/express/lib/router/layer.js:95:5)
    at /srv/node_modules/express/lib/router/index.js:281:22
    at param (/srv/node_modules/express/lib/router/index.js:354:14)
    at param (/srv/node_modules/express/lib/router/index.js:365:14)
    at param (/srv/node_modules/express/lib/router/index.js:365:14)
    at Function.process_params (/srv/node_modules/express/lib/router/index.js:410:3)

这是当前代码。先前的代码也返回上述错误。

exports.updateLike = function (req, res) {

    const postId = req.params.postId;
    const userId = req.params.userId;

    db.collection("posts").doc(postId).collection("likes").set({
        uid: userId,
        createAt: Date.now()
    }).then(post => {
        console.log("--- Operation Success ---")
        return res.status(200).json(post.data());
    }).catch(err => { 
        console.log("--- Operation Failure ---")
        return res.status(500).json(err);
    });
}; 

1 个答案:

答案 0 :(得分:0)

您应该写db.collection("posts").doc(postId).collection("likes").doc().set({ ... })而不是db.collection("posts").doc(postId).collection("likes").add({ ... })