I have an app hosted on Heroku (https://trendedge.app) (front-end and back-end are separate apps), and am working on implementing the Heroku Scheduler for basic tasks such as sending emails, and running updates on my MongoDB Atlas database (hit an API, update MongoDB w/ Mongoose).
For the MongoDB updates, I currently hit an admin route on the front-end, and the updates start running on the backend. Easy PZ.
To setup the Heroku scheduler, though, it requests a node.js command (seen here) ...
... 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.
Can require just the necessary startups from index.js in schedule.js. In this instance just the validation and mongodb startups
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();
}