Home > Net >  How to run Mongoose/MongoDB updates/queries in node.js backend without starting the server? (Heroku
How to run Mongoose/MongoDB updates/queries in node.js backend without starting the server? (Heroku

Time:03-09

I have an app hosted on Heroku (Heroku Scheduler Instructions

... and this makes sense, but if my connection to MongoDB atlas is made upon the starting up the server ('npm start', i.e. 'node index.js'), then how do I run a node command to update MongoDB, when the server hasn't been started yet?

For example, if I run "node updateDB.js", it will error out because there is no server running, and connection to Mongo has yet to be established.

Any insight to how I can setup/test these scheduled node functions (without starting up the server?) would be greatly appreciated.

CodePudding user response:

Can require just the necessary startups from index.js in schedule.js. In this instance just the validation and mongodb startups

CodePudding user response:

for a run single file and connect with database to perform some task. you can try this way.

mongodb = require('mongodb');
config = module.exports = require("/home/node/myclass/crons/config.json");

var MongoClient = mongodb.MongoClient;
ObjectId = module.exports = mongodb.ObjectID;
var dbConnUrl = 'mongodb://'   config.DB_USERNAME   ':'   config.DB_PASSWORD   '@'   config.DB_HOST   ':'   config.DB_PORT   '/'   config.DB_NAME;
console.log("dbConnUrl >> ", dbConnUrl);
MongoClient.connect(dbConnUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, dclient) {
    if (err) {
        console.log("mongodb connection error >> ", err);
        process.exit();
    } else {
        db = module.exports = dclient.db();
        console.log("---------------------------mongodb connected-----------------------");
        run();
    }
});

async function run() {
    await db.collection("notification_token").find({}).toArray();
    process.exit();
}
  • Related