Mon Jul 31 2023

MongoDB Connection using Mongoose

Node JS153 views
MongoDB Connection using Mongoose

File Name: mongodb-nodejs-connection.js

const mongoose = require("mongoose");

const dbURi = "mongodb://localhost:27017";

const options = {
    autoIndex: true,
    serverSelectionTimeoutMS: 5000,
    socketTimeoutMS: 45000,
    family: 4
}

async function connectDB() {
    try {
        if(mongoose.connection.readyState != 1) {
            await mongoose.connect(dbURi, options);
            console.log("Database connected!");
        } else {
            console.log("Database already connected!");
        }
    } catch(err) {
        console.error(err);
        process.exit(1);
    }
}

module.exports = {connectDB}

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.