I need to pass the connection to mongo from index.js to the other routes, I think it is possible to create a file with the instructions that define the connection with the database, so that I can recall it within the other routes, but I have no idea how it can be done. The other examples on this forum didn't help me a lot. I will attach the code below.
//Database connection
mongoose.connect("mongodb://localhost:27017/codingWaifus", {useNewUrlParser: true}, function(err, db){
if(err){
console.log(err);
}
else{
console.log("Connected to "+mongoose.connection.name+" on Port: "+mongoose.connection.port);
}
});
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
You can do this in the following way:
db.js
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();
const connectDB = () => {
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection
.once('open', () => {
console.log('Connection to the DB established');
})
.on('error', (err) => {
console.log('Error occured while connecting to the DB', err);
})
}
module.exports = connectDB;
index.js
const connectDB = require('./db');
// Connecting to the DB
connectDB();
But why do you want to call the MongoDB connection again when you have already established the connection on the first place?