skip to Main Content

I’m trying to connect to my MongoDB localhost but it just won’t connect. What happens is when I go to /admin, it just keeps loading and I get no messages, no nothing in the logs. I have no idea why. This is my router file that uses the connection:

const express = require('express');
const debug = require('debug')('app:adminRouter');
const mongoose = require('mongoose');
const users = require('../data/users.json');

const adminRouter = express.Router();

adminRouter.route('/').get((req, res) => {
    const url = "mongodb://localhost:27017"; // process.env.DBURL
    const dbName = "workplace_incident_reporter";

    (async function mongo(){
        let client;
        try {
            client = await mongoose.connect(url, 
                { useNewUrlParser: true, useUnifiedTopology: true });
            debug('Connected to mongoDB');

            const db = client.db(dbName);

            const response = await db.collection('Users').insertMany(users);
            res.json = response;
        } catch (error){
            debug(error.stack);
        }
    })
});

module.exports = adminRouter;

Here is a picture of my MongoDB Compass window. This is only for URL references:
MongoDB Compass Window

2

Answers


  1. Chosen as BEST ANSWER

    I changed the URL from mongodb://localhost:27017 to mongodb://127.0.0.1:27017


  2. Your function mongo doesn’t run that way! change it into something like this:

    const db_url = 'mongodb://localhost:27017'
    const db_main = 'db-main'
    
    const connectDB = mongoose.connect(
      `${db_uri}/${db_main}`,
      {
        useNewUrlParser: true,
      },
      (err) => {
        if (!err) {
          console.log("MongoDB Connection Succeeded.");
        } else {
          console.log("Error in DB connection: " + err);
        }
      }
    )

    Please consider that you can call the mongoDb connection once at the server.js file

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search