javascript - 将新文档插入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);
});
};
解决方案
在评论中你说:
我只想存储一个在添加新帖子时自增的数字。
Firestore 无法做到这一点。没有像某些 SQL 数据库中那样的自动增量字段。这是因为自动增量值不会按照 Firestore 要求的方式进行缩放。
如果您想要像这样增加值,则需要在其他地方跟踪该值,例如另一个文档或其他来源,并为您添加的每个文档复制更新后的数字。
推荐阅读
- python - 如何使用 Python 计算 csv 中唯一值的数量
- c# - 什么是 WebForm/WebBrowser 中的 NewWindow2 和 NewWindow3
- excel - 如何解决 VBA 上的错误
- tensorflow - 如何在 Tensorflow 2 中使用具有急切模式的可初始化迭代器为 ON
- javascript - 在 UL、LI 和标签内的 Bootstrap 下拉列表中获取选中复选框的 id,然后根据是否选中其他复选框
- css - 向页面添加多个 visualforce 组件时出现问题
- java - 使用 libGDX 以小 (<0.5) 比例渲染字体时出现问题
- javascript - AdonisJS request.post() 为空
- c++ - AVL 树节点(打印)
- amazon-web-services - 如何在 aws 控制台而不是 nodejs 上使用 python 运行时选择 ElasticSearch 订阅过滤器