#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 34 of 62medium

How to connect MongoDB with Node.js?

Using MongoDB with Node.js applications.

What You'll Learn

  • Connecting to MongoDB
  • CRUD operations
  • Using Mongoose ODM

Native MongoDB Driver

$ terminalBash
npm install mongodb
code.jsJavaScript
const { MongoClient } = require('mongodb');

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

async function connect() {
  await client.connect();
  const db = client.db('mydb');
  const users = db.collection('users');

  // Insert
  await users.insertOne({ name: 'John', age: 30 });

  // Find
  const user = await users.findOne({ name: 'John' });
  const allUsers = await users.find({}).toArray();

  // Update
  await users.updateOne({ name: 'John' }, { $set: { age: 31 } });

  // Delete
  await users.deleteOne({ name: 'John' });
}

Mongoose ODM

$ terminalBash
npm install mongoose
code.jsJavaScript
const mongoose = require('mongoose');

// Connect
mongoose.connect('mongodb://localhost:27017/mydb');

// Define Schema
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age: Number,
  createdAt: { type: Date, default: Date.now }
});

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

// CRUD Operations
async function crud() {
  // Create
  const user = await User.create({ name: 'John', email: 'john@example.com' });

  // Read
  const users = await User.find({});
  const one = await User.findById(id);
  const byEmail = await User.findOne({ email: 'john@example.com' });

  // Update
  await User.findByIdAndUpdate(id, { name: 'Jane' }, { new: true });

  // Delete
  await User.findByIdAndDelete(id);
}