Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
How to load MongoDb connection and queries together from an external file in nodejs

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!