Recommand · October 16, 2021 0

Write a function to increment view count in Node.js?

This question is for a Node.js blog project.

I have a blog and I know how to create a new post. This post has a title, and content and date, etc., but I also wanna know how many times the post was viewed.

For this I have the following logic:

  1. Create a model schema for user with "viewCount".
  2. Create a button called "Apply" using Handlebars with an id.
  3. Each time the the button is clicked it increments the number by one.
  4. Store the number in MongoDB.
  5. Sort the post by viewCount.

So the most viewed post will appear first place.

Can you please help me with this? Thank you!

This is the route with the logic:

router.get('/', (req, res)=>{
    const perPage = 10;
    const page = req.query.page || 1;

    let dateNow = Date.now();

    let addHere = document.getElementById('addHere');
    let button = document.getElementById('applyBtn');
    let counter = 0;

    Post.find({})
        .sort({date: 'desc'})
        .skip((perPage*page)-perPage)
        .limit(perPage)
        .then(posts => {
            posts.forEach(post => {
                post.deadlinePassed = dateNow > post.dateToApply

                button = function add() {
                    counter += 1;
                    addHere.textContent = counter;
                }

            })

            Post.count().then(postCount=>{
                Category.find({}).then(categories => {
                    res.render('home/index', {
                        posts: posts,
                        categories: categories,
                        current: parseInt(page),
                        pages: Math.ceil(postCount/perPage)
                    });
                });
            });
        });
});

And this is the Handlebars:

<div class="row">
    <div class="col-12">
        <h1>Home page</h1>
        {{#each posts}}
            <div class="card mb-4">
                <img class="img-fluid" src="/uploads/{{ file }}" alt="Kep">
            </div>
            <div class="card-body">
                <h2 class="card-title">{{title}}</h2>
                <p class="card-text">{{body}}</p>
                <p>{{generateDate dateToApply 'MMMM DD YYYY'}}</p>
                <a href="/post/{{id}}" class="btn btn-primary">More</a>

                <button id="applyBtn" onclick="add()" class="btn btn-info" {{#if deadlinePassed}} disabled {{/if}}>Apply</button>


            </div>

            <div id="addHere" class="card-footer">
            0
            </div>

            <div class="card-footer">
                Date of post {{ generateDate date 'MMMM DD YYYY'}}
            </div>
        {{/each}}
        <ul class="pagination justify-content-center">
            {{#pagination current=current pages=pages}}{{/pagination}}
        </ul>
    </div>
</div>

So I have this route. This is where the logic goes.

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