0
0
Node.jsframework~5 mins

MongoDB connection with mongodb driver in Node.js

Choose your learning style9 modes available
Introduction
Connecting to MongoDB lets your Node.js app store and get data easily.
When you want to save user info from a website.
When you need to read data from a database to show on a page.
When you want to update or delete records in your app.
When you build a backend that talks to a database.
When you want to keep data safe and organized.
Syntax
Node.js
import { MongoClient } from 'mongodb';

const uri = 'your_mongodb_connection_string';
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
    // Use the client here
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Replace 'your_mongodb_connection_string' with your actual MongoDB URI.
Always use async/await to handle the connection properly.
Examples
Connects to a local MongoDB server running on default port 27017.
Node.js
import { MongoClient } from 'mongodb';

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

async function run() {
  await client.connect();
  console.log('Connected to local MongoDB');
  await client.close();
}

run();
Connects to a MongoDB Atlas cloud database using a connection string with username and password.
Node.js
import { MongoClient } from 'mongodb';

const uri = 'mongodb+srv://user:password@cluster0.mongodb.net/mydb?retryWrites=true&w=majority';
const client = new MongoClient(uri);

async function run() {
  await client.connect();
  console.log('Connected to MongoDB Atlas');
  await client.close();
}

run();
Sample Program
This program connects to a local MongoDB, inserts one document into 'testcollection' in 'testdb', then closes the connection.
Node.js
import { MongoClient } from 'mongodb';

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

async function run() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
    const database = client.db('testdb');
    const collection = database.collection('testcollection');
    const doc = { name: 'Alice', age: 25 };
    const result = await collection.insertOne(doc);
    console.log('Inserted document id:', result.insertedId);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
OutputSuccess
Important Notes
Make sure MongoDB server is running before connecting.
Use try/finally to close the connection even if errors happen.
The insertedId is a unique ID MongoDB creates for each document.
Summary
Use MongoClient from 'mongodb' package to connect.
Always connect and close the client properly with async/await.
Replace the URI with your MongoDB server address.