Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing mongoimport inside code with Javascript/Node.js

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

like image 778
theGreenCabbage Avatar asked Mar 15 '13 16:03

theGreenCabbage


People also ask

Can I use node js code in JavaScript?

Node.js allows you to run JavaScript on the server.

How do you perform a CRUD operation in node JS?

CRUD (Create, Read, Update, Delete) operations allow you to work with the data stored in MongoDB. The CRUD operation documentation is categorized in two sections: Read Operations find and return documents stored within your MongoDB database. Write Operations insert, modify, or delete documents in your MongoDB database.

Can I use JavaScript with MongoDB?

MongoDB supports JavaScript through the official Node. js driver. You can connect your Node. js applications to MongoDB and work with your data.


1 Answers

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])

like image 69
Alexandru Olaru Avatar answered Oct 04 '22 20:10

Alexandru Olaru