简体   繁体   中英

How to write nodejs script output in mongo?

I want to make nodejs script, witch should ping host and write result in mongodb. Now I am using agenda to create a job and start a ping at the right time. 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.

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:

node seeding_scripts\ping_results.js

ping_results.js file.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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