![](/img/trans.png)
[英]How to save one document into two different collections of same database in mongodb
[英]Can you check two different firestore collections before updating a document in each one?
我一直在使用 Firestore、云函数和 Admin SDK 来构建博客/论坛。 有一个 forumPosts 集合和一个 forumComments 集合。 评论可以有子评论,因此 forumComments 集合中的每个评论都有帖子的 ID 和其父评论的 ID(直接在帖子(顶级)上的评论有一个 parentId = 到 postId)。
我的问题是,当发表评论时,我需要首先检查博客文章是否存在,然后是否存在父评论,如果两个条件都为真,则更新帖子的评论计数和父评论的评论计数。 .. 然后将新评论添加到 forumComments 集合。 显而易见的答案是一步一步地执行每个步骤,但这将需要 4 次文档读取(4 次获取)和 3 次文档写入(2 次更新和 1 次添加)......这将使添加评论成为一项昂贵的操作。
我对 Promise 没有很好的处理,并且正在积极尝试学习更多……但我似乎无法弄清楚这个功能。 有没有更有效的方法来做我想做的事情? 非常感谢任何和所有帮助!
这是我的函数的当前结构:
index.js(包含http请求和路由)
app.post('/forumPost/:forumPostId/:parentId/comment', FBAuth, postOneForumComment);
exports.api = functions.https.onRequest(app);
forumPosts.js(包含 postOneForumComment 函数)
enter code hereexports.postOneForumComment = (req, res) => {
if (req.body.body.trim() === '') return res.status(400).json({ comment: 'Must not be empty' }); //check if entry is empty
const newComment = {
body: req.body.body,
createdAt: new Date().toISOString(),
forumPostId: req.params.forumPostId,
parentId: req.params.parentId,
username: req.user.username,
userImage: req.user.imageUrl,
commentCount: 0,
likeCount: 0
};
db.doc(`/forumPosts/${req.params.forumPostId}`).get()
.then((postDoc) => {
const promises = [];
if (!postDoc.exists) {return res.status(404).json({ error: 'Post not found' });} //check if the post exists
db.doc(`/forumComments/${req.params.parentId}`).get()
.then((comDoc) => {
if (!comDoc.exists) {return res.status(404).json({ error: 'Comment not found' });} //check if the comment exists
const comProm = comDoc.ref.update({ commentCount: comDoc.data().commentCount + 1 }); //increment the comment count on the parent comment
const postProm = postDoc.ref.update({ commentCount: postDoc.data().commentCount + 1 }); //increment the comment count on the post
return promises.push(comProm, postProm);
})
.catch((err) => {
console.log(err);
return res.status(500).json({ error: 'Something went wrong during the comment retrival' });
});
return Promise.all(promises);
})
.then(() => {
return db.collection('forumComments').add(newComment); //add the new comment
})
.then(() => {
console.log("8");
res.json(newComment);
})
.catch((err) => {
console.log(err);
res.status(500).json({ error: 'Something went wrong' });
});
};
考虑在您的 Web 服务器中添加newComment
。 您可以使用 Cloud Functions 异步更新评论计数。 这使您的网络路由只有 2 次读取和 1 次写入。
在 Cloud Function 中,您也许可以假设parentId
和forumPostId
已经存在(即发布评论的代码进行了必要的验证),然后使用FieldValue.increment()
进行 2 次写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.