iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

MongoDB (mongoose)

Connecting Node to MongoDB: official driver vs Mongoose, pooling, queries, indexes, and the patterns for production apps.

Node — MongoDB

EXAMPLE
# Install: npm install mongodb
import { MongoClient } from 'mongodb';

# ===== Connect =====
const client = new MongoClient(process.env.MONGO_URI, {
  maxPoolSize: 50,
  minPoolSize: 5,
  serverSelectionTimeoutMS: 5000,
});
await client.connect();
const db = client.db('shop');

# ===== Collection queries =====
const users = db.collection('users');

await users.insertOne({ email: 'a@x.io', name: 'Alex' });
await users.insertMany([{ email: 'b@x.io' }, { email: 'c@x.io' }]);

const u = await users.findOne({ email: 'a@x.io' });
const all = await users.find({ age: { $gt: 18 } }).limit(50).toArray();

await users.updateOne({ _id: id }, { $set: { name: 'Sam' } });
await users.deleteOne({ _id: id });

# ===== Aggregation =====
const stats = await db.collection('orders').aggregate([
  { $match: { status: 'paid' } },
  { $group: { _id: '$customer_id', total: { $sum: '$amount' }, n: { $sum: 1 } } },
  { $sort: { total: -1 } },
  { $limit: 10 },
]).toArray();

# ===== Transactions (replica set required) =====
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    await accounts.updateOne({ _id: from }, { $inc: { balance: -50 } }, { session });
    await accounts.updateOne({ _id: to },   { $inc: { balance:  50 } }, { session });
  });
} finally {
  await session.endSession();
}

# ===== Indexes =====
await users.createIndex({ email: 1 }, { unique: true });
await orders.createIndex({ customer_id: 1, created_at: -1 });

# ===== Mongoose (ODM) =====
# Install: npm install mongoose
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGO_URI);

const UserSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  name: String,
  created_at: { type: Date, default: Date.now },
});
const User = mongoose.model('User', UserSchema);

const u = await User.create({ email: 'a@x.io', name: 'Alex' });
const found = await User.findOne({ email: 'a@x.io' });

# Driver vs Mongoose:
# - Driver: lighter, closer to MongoDB
# - Mongoose: schemas, validation, middleware, populate (joins)
# Pick driver for performance / control; Mongoose when schema discipline + relations help.

# ===== Connection lifecycle =====
# Connect ONCE per process; reuse across requests.
# Close on shutdown for clean exits:
process.on('SIGTERM', async () => {
  await client.close();
  process.exit(0);
});

# ===== Patterns =====
# - Connection pool sized for concurrency
# - Indexes BEFORE production traffic
# - Transactions only when atomicity matters (slower)
# - Replica set in prod; standalone only for dev

# ===== Pitfalls =====
# - Connecting per request (slow + connection leak)
# - Schema-less production data drift; use validation
# - Forgetting indexes on hot query paths
# - Mixing driver + Mongoose in the same codebase inconsistently

Why it matters

Node to MongoDB: official driver for performance, Mongoose when schemas + relations earn their ceremony. Connection pool once per process, indexes before traffic, transactions sparingly. Standard CRUD + aggregation + indexes covers most apps.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import { MongoClient } from 'mongodb';
const client = new MongoClient(uri);
const db = client.db('shop');
const users = await db.collection('users').find().toArray();
Try it Yourself »

Discussion

Loading…