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:
2
Answers
I changed the URL from
mongodb://localhost:27017
tomongodb://127.0.0.1:27017
Your function mongo doesn’t run that way! change it into something like this:
Please consider that you can call the mongoDb connection once at the server.js file