node.js - 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
},
解决方案
对,所以如果你想在 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});
});
});
});
(注意async
and await
。这些是更现代的等价物.then()
and.catch()
你似乎仍在使用)
话虽如此,虽然这将是您的 MVP,但您可能希望考虑在每次有人访问该帖子时设置一些 cookie。这样,每次后续请求都会将 cookie 发送到您的浏览器,您可以确保用户无法通过一遍又一遍地刷新网站来增加一百万次浏览量:P 可以选择通过存储 IP 来实现相同的目的请求来自。
推荐阅读
- amazon-dynamodb - DynamoDB - 删除项目
- angular - 如何在不同的角度库之间正确共享数据?
- python-3.x - 为什么函数在python中改变列表值
- php - CodeIgniter3 order_by() 如何在活动记录中使用 NULLS LAST
- kibana - 如何在操作消息模板中将查询结果格式化为 json
- javascript - 使用 WordPress API 反应应用程序 - 图像问题
- python - 在 django 视图中解析 json 对象
- java - Android 应用程序在检查 REST API 后收到推送通知
- sql-server - 在 SQL Server 中创建 PK
- javascript - 未处理 IDBDatabase 事务错误