Home > Net >  update mongodb every 24hr nodejs
update mongodb every 24hr nodejs

Time:11-05

I'm working on a project that uses a third data API that updates every 24hours, I have a code that inserts the data of the third api into MONGODB every time that i run it with nodeJS, how can i run a code that sends a signal and updates the data on mongoDB every24hours and adds new accounts if new accounts were created on the third party api.

this is the code that i'm currently using to insert the data from the third API.

const fetch = (...args) =>
import('node-fetch').then(({ default: fetch }) => fetch(...args));
const mongoose = require('mongoose');

mongoose.connect("mongodb://mymongoDBURL/mymongoDBTABLE");

const postSchema = new mongoose.Schema({

    id: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    status: {
        type: String,
        required: false
    },

});

const Post = mongoose.model('players', postSchema);

async function getPosts() {
    const getPlayers = await fetch("http://localhost:3008/api/players"); <--- THIRD PARTY API RUNNING FROM MY LOCALHOST 
    const response = await getPlayers.json();
    for( let i = 0;i < response.players.length; i  ){

const post = new Post({
    id: response.players[i]['id'],
    name: response.players[i]['name'],
    status: response.players[i]['status'],
});
post.save();


    }

}
getPosts();```

CodePudding user response:

I would recommend trying to run that code within a cronjob. You can either implement the cronjob directly into your code by using "Node-Cron" for example, which is a package implementing cron into nodejs.

If you want to run it every 24h, you could probably use the following snippet.

import { schedule } from 'node-cron';

schedule('0 0 * * *', async () => {
    //Insert your code which should be executed every 24 hours here
    await getPosts();
});

This would run the code once a day at midnight.

You could also try to run the cronjob directly from your os, for example with crontab on linux.

Or a complete different approach would be running it with the setInterval() function, which would look something like this:

setInterval(async () => {
    //Insert your code which should be executed every 24 hours here
    await getPosts();
}, 24 * 60 * 60 * 1000);

The biggest difference would probably be the fact that the setInterval approach would start instantly and the cronjob would wait for midnight. Except the outcome would probably be nearly the same.

  • Related