Navigation

Node.js

How to Connect to MongoDB with Mongoose

Connect to MongoDB database in Node.js using Mongoose ODM. Simple setup with connection string and basic error handling.

Table Of Contents

Problem

You need to connect your Node.js application to a MongoDB database using Mongoose for data operations and schema management.

Solution

const mongoose = require('mongoose');

// Basic connection
async function connectMongoDB() {
  try {
    await mongoose.connect('mongodb://localhost:27017/myapp', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    
    console.log('Connected to MongoDB');
  } catch (error) {
    console.error('MongoDB connection error:', error);
    process.exit(1);
  }
}

// Connection with options
async function connectWithOptions() {
  const options = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    maxPoolSize: 10,
    serverSelectionTimeoutMS: 5000,
    socketTimeoutMS: 45000,
  };
  
  await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/myapp', options);
}

// Connection event handlers
mongoose.connection.on('connected', () => {
  console.log('Mongoose connected to MongoDB');
});

mongoose.connection.on('error', (error) => {
  console.error('Mongoose connection error:', error);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose disconnected');
});

// Graceful shutdown
process.on('SIGINT', async () => {
  await mongoose.connection.close();
  console.log('MongoDB connection closed');
  process.exit(0);
});

// Simple schema example
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

Install Mongoose:

npm install mongoose

Explanation

Use mongoose.connect() with your MongoDB connection string. The connection is asynchronous, so wrap it in try-catch for error handling.

Set up event listeners for connection states and implement graceful shutdown to properly close the database connection when your app terminates.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Node.js