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

150
Visualizações
callback(new MongoError(document)); Not connecting to MongoDB Database? (Node.js)

I am writing this code which is a starter to connect to a MongoDB database but the problem is that I am not connecting to it in the first place. I have successfully connected to a database before by whitelisting my IP but not sure why this time it's not working. Also the connection string is correct because I have used it before and I am trying to connect to the same database but my code is not letting me for some reason.

Here is my code:

app.js

const express = require("express");
const app = express();

const db = require('./db/connection.js');

db.once('open', ()=>{
    console.log("connected to database");
    const server = app.listen(8080,()=>console.log("listening"));
});



app.use(express.static("public"));
app.use(express.urlencoded({extended:true}));

db/connection.js

let mongoose = require('mongoose');

let mongoDB = `enter mongo db connection string here`;

mongoose.connect(mongoDB,{ useNewUrlParser: true, useUnifiedTopology: true });

module.exports = mongoose.connection;
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Try to declare a dedicated async function to handle DB connection:

let mongoose = require('mongoose');

let mongoDB = `enter mongo db connection string here`;

const connectDB = async () => {
    try {
        const conn = await mongoose.connect(mongoDB, {
            useNewUrlParser: true,
            useUnifiedTopology: true
          });
      
          console.log(`MongoDB connected: ${conn.connection.host}`);
    } catch (err) {
        console.log(err);
        process.exit(1);
    }
}

module.exports = { connectDB };

Then, in app.js:

const { connectDB } = require('./db/connection');

// Connect to the DB
connectDB();

// Middleware init
app.use(express.static("public"));
app.use(express.urlencoded({extended:true}));

// Launch the server
const server = app.listen(8080,()=>console.log("listening"));
about 4 years ago · Santiago Trujillo 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