I have a node.js script which is used to connect MongoDB and load data. Initially I put the multiple queries inside the script and I was able to load by running the script.
Now I need to dynamically load the entire connection and the query from an external file. I tried in the below way but we are not able to read the db connection and queries together like this since we are passing as functions. Any solution to read the entire query and connection from an external file?
index.js code
var MongoClient = require('mongodb').MongoClient;
const file = require('./assets/queryConfig');
const url = 'mongourl';
MongoClient.connect(url, {useNewUrlParser: true}, {slave_ok: true}, function (err,db){
if(err) throw err;
var dbo = db.db('mongoDBName');
file.queryList.forEach(query => {
query;
});
db.close();
});
queryConfig.js - keep the queries as an array of strings.
var queryList = [
`db.collection('collectionName').insertMany([{'id':1,'data':'test'},
{'id':2,'data':'test2'}]);`,
`db.collection('collectionName2').insertMany([{'id':3,'data':'test3'},
{'id':4,'data':'test4'}]);`
]
exports.queryList = queryList;
Kindly provide if anyone has any solution for this.
I think you should use mongo shell to run the script
https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/ https://nodejs.dev/learn/writing-files-with-nodejs
In the nodejs script
const { exec } = require("child_process");
file.queryList.forEach(query => {
// write query to file "script.js"
....
exec("mongo localhost:27017/test script.js", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
});