You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nodejs博客post访问量view count无法保存到数据库问题求助

问题排查

  • 你的代码存在3个核心错误导致计数无法写入数据库:
    1. GET请求默认不会携带请求体,你从req.body.viewCount取值得到的是undefined,自增操作完全无效
    2. 你定义的counter是普通数值类型,没有Mongoose文档的save()方法,调用counter.save()不会触发数据库写入
    3. 你修改完字段后没有对查询返回的post文档实例执行保存操作,修改不会同步到数据库

修复方案

方案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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:48:02