首页 > 解决方案 > Nodejs发布视图计数保存数据库

问题描述

我是新手,但我有一个基本的 nodejs 博客应用程序。我知道如何创建新帖子并执行 CRUD,但我也想计算帖子被查看的次数。没有注册,所以我只是尝试告诉应用程序每次点击 url 时,如 localhost:3000/post/{{id}} 计数器应该增加一。

我有一个简单的逻辑,但我无法将其保存到数据库中。我在 Compass 中检查它,查看次数仍然为 0。

这是邮寄路线:

router.get('/post/:slug', (req, res) => {
    Post.findOne({slug: req.params.slug})
        .populate({path: 'comments', populate: {path: 'user', model: 'users'}})
        .populate('user')
        .then(post => {
            let counter = req.body.viewCount
            counter++
            counter.save()
            Category.find({})
                .then(categories => {
                    res.render('home/post', {post: post, categories: categories});
                });
        });
});

module.exports = router; 

和模型(视图计数部分):

viewCount: {
        type: Number,
        default: 0
    },

标签: node.jspostviewcountblogs

解决方案


对,所以如果你想在 mongodb 中增加一个值,我想向你推荐一个类似的帖子:如何在 Mongoose 中增加一个数字值?(或者你知道......任何随机的博客官方文档

我对这将如何应用于您的代码的有根据的猜测如下

router.get('/post/:slug', async (req, res) => {
    await Post.findOneAndUpdate({slug : req.params.slug}, {$inc : {'counter' : 1}});
    await Post.findOne({slug: req.params.slug})
        .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});
                });
        });
});

(注意asyncand await。这些是更现代的等价物.then()and.catch()你似乎仍在使用)

话虽如此,虽然这将是您的 MVP,但您可能希望考虑在每次有人访问该帖子时设置一些 cookie。这样,每次后续请求都会将 cookie 发送到您的浏览器,您可以确保用户无法通过一遍又一遍地刷新网站来增加一百万次浏览量:P 可以选择通过存储 IP 来实现相同的目的请求来自。


推荐阅读