I new to this stuff but I have a basic nodejs blog app. I knew how to create a new post and do the CRUD but I also want to count how many times a post was viewed. There is no registration so I just try to tell the app the each time the url was hit like localhost:3000/post/{{id}} the counter should goes up by one.
I have a simple logic but I can't save it to database. I check it in Compass and view count remains 0.
This is the post route:
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;
And the model (the view count part):
viewCount: {
type: Number,
default: 0
},