【问题标题】:Can you check two different firestore collections before updating a document in each one?您可以在更新每个文档之前检查两个不同的 Firestore 集合吗?
【发布时间】:2020-01-09 16:59:46
【问题描述】:

我一直在使用 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' });
 });
};

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore firebase-admin


    【解决方案1】:

    考虑在您的网络服务器中添加newComment。您可以使用云函数异步更新评论计数。这使您的网络路由只需 2 次读取和 1 次写入。

    在 Cloud Function 中,也许您可​​以假设 parentIdforumPostId 已经存在(即发布评论的代码进行了必要的验证),然后使用 FieldValue.increment() 进行 2 次写入。

    【讨论】:

    • 嘿Hiranya,这是一个更好的解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多