Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to Node.js

How to Connect Node.js with MongoDB?

Node.js2,340 viewsBy Muhammad Fareed
nodejsmongodbdatabaseconnection

How to Connect Node.js with MongoDB

Learn how to establish a connection between Node.js and MongoDB using the official MongoDB driver or Mongoose ODM.

Installation

npm install mongodb
# or using Mongoose
npm install mongoose

Basic Connection (Native Driver)

const { MongoClient } = require('mongodb');

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function connect() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");
    const database = client.db('myDatabase');
    const collection = database.collection('users');
    return collection;
  } catch (error) {
    console.error(error);
  }
}

Using Mongoose

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error', err));

Best Practices

  • Use environment variables for connection strings
  • Implement connection pooling
  • Handle errors properly
  • Close connections when done