Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda