首页 > 解决方案 > 将新文档插入firebase时如何增加帖子ID?

问题描述

有没有办法增加添加到数据库中的每个文档的帖子 ID,所以我的数据看起来像这样。

第一个插入:

{
    "createdAt": "2020-09-27T21:35:12.276Z",
    "postId": "1",
    "body": "This is my first post",  
}

第二次插入:

{
    "createdAt": "2020-09-27T21:37:39.165Z",
    "postId": "2",
    "body": "This is my second post",  
}
exports.postOnePost = (req, res) => {
  if (req.body.body.trim() === "") {
    return res.status(400).json({ body: "Body must not be empty" });
  }

  const newPost = {
    createdAt: new Date().toISOString(),
    postId: ,
    body: req.body.body,
  };

  db.collection("posts")
    .add(newPost)
    .then((doc) => {
      console.log(doc.id)
    })
    .catch((err) => {
      res.status(500).json({ error: "something went wrong" });
      console.error(err);
    });
};

标签: javascriptnode.jsfirebasegoogle-cloud-firestore

解决方案


在评论中你说:

我只想存储一个在添加新帖子时自增的数字。

Firestore 无法做到这一点。没有像某些 SQL 数据库中那样的自动增量字段。这是因为自动增量值不会按照 Firestore 要求的方式进行缩放。

如果您想要像这样增加值,则需要在其他地方跟踪该值,例如另一个文档或其他来源,并为您添加的每个文档复制更新后的数字。


推荐阅读