Reputation: 57
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;
Upvotes: 0
Views: 2912
Reputation: 13274
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"));
Upvotes: 1