Home > Blockchain >  Localhost MongoDB Connection with Mongoose not working
Localhost MongoDB Connection with Mongoose not working

Time:10-25

I'm trying to connect to my MongoDB localhost but it just won't connect. 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

CodePudding user response:

Looks like you are mixing mongoose and mongodb. Also, the mongo function is not executed. Try to change your code to (make sure to npm i mongodb):

const express = require('express');
const debug = require('debug')('app:adminRouter');
const users = require('../data/users.json');
const { MongoClient } = require('mongodb');

const adminRouter = express.Router();

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

    const client = new MongoClient(url);
    await client.connect();

    const db = client.db(dbName);

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

module.exports = adminRouter;

CodePudding user response:

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

  • Related