Executing mongoimport inside code with Javascript/Node.js

javascript, json, mongodb, mongoimport, node.js

Solution

This is how I do it in my code

let exec = require('child_process').exec
let command = 'mongoimport -d database -c collection --file import.json'
exec(command, (err, stdout, stderr) => {
  // check for errors or if it was succesfuly
  cb()
})

I exec the mongoimport command and then I do pass the cb next the code to be accesible, or if you do not use an asynchronous style you can do it synchronously with `child_process.execSync(command[,options])`

Problem

Is there any library available in node.js/javascript that allows an individual to use `mongoimport` in code? To my understanding, mongoimport is kinda like an .exe, which you have to execute it first before being able to use its text input environment. Is it possible to execute mongoimport in my code and then parse whatever commands I need directly in my code? My current algorithm involves: ``` fs.appendFile('log.txt',JSON.stringify(obj, null, 2)); ``` obj is an object which specifies what functions to parse into `JSON.stringify` with the `res` method of node.js (which requests HTTP responses) ``` var obj = {}; obj.url = hostNames[i]; obj.statusCode = res.statusCode; obj.headers = res.headers; ``` Then I use mongoimport to import this JSON doc into my MongoDB. `mongoimport --host localhost -db scrapeapp -collection scrape --file log.txt --jsonArray` This method is obviously inefficient. I would like to do all these steps in one going. Help appreciated

Original source

Related problems