[英]How to write nodejs script output in mongo?
I want to make nodejs script, witch should ping host and write result in mongodb.我想制作nodejs脚本,女巫应该ping主机并将结果写入mongodb。 Now I am using agenda to create a job and start a ping at the right time.现在我正在使用议程来创建工作并在正确的时间开始 ping。 How to write the result of execution to the database?如何将执行结果写入数据库? I tried to use the Mongoclient, but it seems to me that this is a little not what I need.我尝试使用 Mongoclient,但在我看来,这有点不是我需要的。
var ping = require('ping');
const mongo = require('mongodb');
const MongoClient = mongo.MongoClient;
const url = 'mongodb://127.0.0.1:27017/test';
const config = ['10.10.4.45']
const Agenda = require('agenda');
const dbURL = 'mongodb://127.0.0.1:27017/test';
const agenda = new Agenda({
db: {
address: dbURL,
collection: 'jobs',
options: {
useNewUrlParser: true,
useUnifiedTopology: true
}
}
});
let counter = 0;
agenda.define('Ping host 10.10.4.45', async job => {
counter++;
await console.log('Ping test #'+counter);
for(let host of config){
let res = await ping.promise.probe(host);
console.log(res.host, res.alive);
}
});
(async function() {
await agenda.start();
await agenda.every('5 seconds', 'Ping host 10.10.4.45');
})();
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("test");
var myobj = [
{ name: 'John', address: 'Highway 71'}
];
dbo.collection("ping_results").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});
Save the below code in a file say ping_results.js
inside your repository in a folder seeding_scripts
for example and then run it using below command:将以下代码保存在一个文件中,例如ping_results.js
在您的存储库中的文件夹中的seeding_scripts
,然后使用以下命令运行它:
node seeding_scripts\ping_results.js
ping_results.js
file. ping_results.js
文件。
const MongoClient = require('mongodb').MongoClient;
const DB_URI = "mongodb://localhost:27017/db_name";
const options = {
useNewUrlParser: true
};
MongoClient.connect(DB_URI, options, function (err, client) {
if (err) {
console.log("ERROR: Failed to connect to database.");
console.log(err);
return;
}
let dbName = DB_URI.split("/", -1).pop();
let collectionName = "ping_results";
let db = client.db(dbName);
console.log(`Connected to ${dbName} database successfully.`);
var data = [
{ name: 'John', address: 'Highway 71' }
];
db
.collection(collectionName)
.insertMany(data)
.then(res => {
console.log(`${res.insertedCount} Documents inserted successfully.`);
console.log("Database connection closed.");
client.close();
})
.catch(err => {
console.log(JSON.stringify(err));
console.log("Database connection closed.");
client.close();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.