【发布时间】:2020-09-27 21:39:57
【问题描述】:
有没有办法为添加到数据库中的每个文档增加帖子 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);
});
};
【问题讨论】:
-
为什么需要这样做?这种策略不能很好地扩展(因为您的自动增量将难以在负载下保持最新)。简单地接受每个文档的随机标识符通常更合适。
add()已经为您提供了该 ID。 -
因为每个帖子都有自己的号码,我想在客户端显示这个号码。我正在为文档使用随机标识符,我只想存储一个在添加新帖子时自增的数字。
标签: javascript node.js firebase google-cloud-firestore