您可以在更新每个文档之前先检查两个不同的Firestore集合吗?

问题描述 投票:0回答:1

我一直在使用Firestore,云功能和Admin SDK来构建博客/论坛。有一个forumPosts集合和一个forumComments集合。评论可以有子评论,因此forumComments集合中的每个评论都有帖子的ID和其父评论的ID(直接在帖子(顶层)上的评论的postId为postId)。

[我的问题是,发表评论时,我需要先检查博客帖子是否存在,然后检查父评论是否存在,并且如果两个条件都成立,请更新帖子的评论计数和父评论的计数评论...,然后将新评论添加到forumComments集合中。显而易见的答案是一步一步地执行每个步骤,但这需要4次文档读取(4次获取)和3次文档写入(2次更新和1次添加)...这将使添加注释成为一项昂贵的操作。

我对诺言没有很好的处理,正在积极尝试学习更多...但是我似乎无法弄清楚这一功能。有没有更有效的方式来做我想做的事情?任何帮助都将不胜感激!

这是我函数的当前结构:

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' });
 });
};
javascript node.js firebase google-cloud-firestore firebase-admin
1个回答
0
投票

考虑只将newComment添加到您的Web服务器中。您可以使用Cloud Function异步更新评论计数。这使您的网络路由只有2次读取和1次写入。

[在Cloud Function中,您可能只是假设parentIdforumPostId已经存在(即,张贴评论的代码已进行了必要的验证),而仅使用FieldValue.increment()做2次写入。

© www.soinside.com 2019 - 2024. All rights reserved.