简体   繁体   中英

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;

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM