【发布时间】:2020-06-01 15:38:10
【问题描述】:
所以,我正在尝试在我的 API 中实现 .increment。我需要每秒更新一次以上的点赞数,这就是为什么我要尝试更新我的 API 来执行此操作。这是我正在尝试实现的确切代码:
const postRef = db
.collection('posts')
.doc(postId);
postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});
当没有与用户句柄关联的当前类似文档时,上面的代码可以完美运行,但是当存在时,
return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
被击中并完美返回错误消息。但是,.then 链的其余部分被击中,这是不应该的。
这是有效的旧代码:
exports.likepost = (req, res) => {
const postId = req.body.postId;
db
.collection('posts')
.doc(postId)
.get()
.then((doc) => {
if(!doc.exists){
return res.status(404).json({'Error': `post ID ${postId} not found`});
}
else{
return db.collection('likes')
.where('postId', '==', postId)
.where('userHandle', '==', req.user.userHandle)
.get();
}
})
.then((likeDoc) => {
if(!likeDoc.empty){
return res.status(404).json({'Error': `${req.user.userHandle} already liked this post`});
}
else{
return db
.collection('posts')
.doc(postId)
.get()
}
})
.then((doc) => {
const oldLikeCount = doc.data().likeCount;
const newLikeCount = oldLikeCount + 1;
return db
.collection('posts')
.doc(postId)
.update({
likeCount: newLikeCount
});
})
.then(() => {
const like = {
userHandle: req.user.userHandle,
postId: postId,
likedAt: new Date().toISOString()
};
return db
.collection('likes')
.add(like);
})
.then(() => {
return res.json({message: `Successfully liked ${postId}`});
})
.catch((err) => {
return res.status(500).json({error: err});
});
}
在这段代码中, res.status(404).json() 被命中,其余的 .then 链不执行,这是完美的。但是这段代码使用了太多的读写操作,并且每秒更新文档的次数不能超过 1 次。
这是有错误的新代码:
exports.likepost = (req, res) => {
const postId = req.body.postId;
db
.collection('likes')
.where('postId', '==', postId)
.where('userHandle', '==', req.user.userHandle)
.get()
.then((likeDoc) => {
if(!likeDoc.empty){
return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
} // It should stop here but it is not.... the code returns the 401 status and the error message so it hits this code, but it doesn't stop the chain
else{
// Update count
const postRef = db
.collection('posts')
.doc(postId);
postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});
}
})
.then(() => {
const like = {
userHandle: req.user.userHandle,
postId: postId,
likedAt: new Date().toISOString()
};
return db
.collection('likes')
.add(like);
})
.then(() => {
return res.json({message: `Successfully liked ${postId}`});
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: err});
});
}
非常感谢任何帮助!!!
【问题讨论】:
标签: javascript node.js express google-cloud-firestore