简体   繁体   English

如何在不启动服务器的情况下在 node.js 后端运行 Mongoose/MongoDB 更新/查询? (Heroku 调度程序)

[英]How to run Mongoose/MongoDB updates/queries in node.js backend without starting the server? (Heroku Scheduler)

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).我在 Heroku ( https://trendedge.app ) 上托管了一个应用程序(前端和后端是单独的应用程序),并且正在努力实现 Heroku 调度程序以执行基本任务,例如发送电子邮件和在我的计算机上运行更新MongoDB Atlas 数据库(点击 API,更新 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.对于 MongoDB 更新,我目前在前端点击了管理路由,更新开始在后端运行。 Easy PZ.简单的PZ。

To setup the Heroku scheduler, though, it requests a node.js command (seen here)...但是,要设置 Heroku 调度程序,它会请求 node.js 命令(见此处)... Heroku 调度程序说明

... and this makes sense, but if my connection to MongoDB atlas is made upon the starting up the server ('npm start', ie 'node index.js'), then how do I run a node command to update MongoDB, when the server hasn't been started yet? ...这是有道理的,但是如果我与 MongoDB atlas 的连接是在启动服务器时建立的('npm start',即'node index.js'),那么我该如何运行节点命令来更新 MongoDB,什么时候服务器还没有启动?

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.例如,如果我运行“node updateDB.js”,它会出错,因为没有服务器在运行,并且尚未建立与 Mongo 的连接。

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.可以从 schedule.js 中的 index.js 只需要必要的启动。 In this instance just the validation and mongodb startups在这个例子中只有验证和 mongodb 启动

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM