Nodejs博客post访问量view count无法保存到数据库问题求助
问题排查
- 你的代码存在3个核心错误导致计数无法写入数据库:
- GET请求默认不会携带请求体,你从
req.body.viewCount取值得到的是undefined,自增操作完全无效 - 你定义的
counter是普通数值类型,没有Mongoose文档的save()方法,调用counter.save()不会触发数据库写入 - 你修改完字段后没有对查询返回的
post文档实例执行保存操作,修改不会同步到数据库
- GET请求默认不会携带请求体,你从
修复方案
方案1:调整现有逻辑适配写法
router.get('/post/:slug', (req, res) => { Post.findOne({slug: req.params.slug}) .populate({path: 'comments', populate: {path: 'user', model: 'users'}}) .populate('user') .then(post => { // 直接修改post文档的viewCount字段 post.viewCount += 1 // 保存post实例到数据库 post.save() .then(() => Category.find({})) .then(categories => { res.render('home/post', {post: post, categories: categories}); }); }); }); module.exports = router;
方案2(更推荐):使用Mongoose原子操作避免并发计数错误
router.get('/post/:slug', (req, res) => { // 查询的同时直接原子更新viewCount,不需要手动save Post.findOneAndUpdate( {slug: req.params.slug}, {$inc: {viewCount: 1}}, // 原子自增1,并发访问场景也不会出现计数偏差 {new: true} // 配置返回更新后的最新文档 ) .populate({path: 'comments', populate: {path: 'user', model: 'users'}}) .populate('user') .then(post => { return Category.find({}) .then(categories => { res.render('home/post', {post: post, categories: categories}); }); }); }); module.exports = router;
你的Post模型的viewCount字段定义无需修改,调整路由代码后即可正常统计访问量。
内容的提问来源于stack exchange,提问作者exitcode_1
相关产品推荐
相关产品推荐

