How to run a number counter continuously with mongodb and node

Viewed 111

sorry but i just started learning about backend web development therefore this question might sound stupid.

right now, my backend only runs when the GET request or POST request is triggered because the logics are in there.

But how do i get my number counter to +1 continuously every 5 seconds in the background?

Since it only gets triggered when i visit my localhost website (app.get)(GET request),

i want it to continuously run to infinity.

is it possible?

My end goal here is to have this so called number counter run continuously at the same rate (assuming i didn't shut the server down), so that when i came back to my page an hour later, the counter should still be running and had already running for 1 hour even though the GET request was triggered only once.

Thanks!

2 Answers

You could use websocket, but just for that is overkill.

Make a route in the server with a 200 response, very simple, no errors.

If anything but 200 is returned the server is down and the counter restarts, create function on the front that keeps requesting that route.You could use many options on that one, but i recommend a setInterval

<div id="counter">1</div>

I used 1 as a starter number.

const interval = 5 // seconds
const htmlElement = document.getElementById("counter")
let counter = 1

function serverStatus() {
    try{
        // Request code here
        counter++
        
    } catch (e) {
        console.error(e)
        counter = 0
    }

    htmlElement.innerHTML = counter
}

setInterval(serverStatus, 5 * 1000)

Change the code to meet your needs tho

This is a basic counter example for MongoDB, you can implement the schema type accordingly in your Node.js

  var table_name_Schema = new mongoose.Schema({
        _id: {type: String, required: true},
        seq: { type: Number, default: 0 }
    });
    var counter = mongoose.model('counter', table_name_Schema);
    
    var entitySchema = mongoose.Schema({
        sort: {type: String}
    });
    
    entitySchema.pre('save', function(next) {
        var doc = this;
        counter.findByIdAndUpdateAsync({_id: 'entityId'}, {$inc: { seq: 1} }, {new: true, upsert: true}).then(function(count) {
            console.log("...count: "+JSON.stringify(count));
            doc.sort = count.seq;
            next();
        })
        .catch(function(error) {
            console.error("counter error-> : "+error);
            throw error;
        });
    });
Related