![](/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.