Sikau

MongoDB · Day 13 · about 25 min

MongoDB from Node.js

The driver, connection handling and ObjectIds.

From shell to server

Everything you typed in the shell works in Node.js with the official driver — the same filters, updates and pipelines, but async. A few app-specific habits make it production-ready.

The official driver

import { MongoClient, ObjectId } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const db = client.db("cafe");

export async function getDish(id) {
  return db.collection("dishes").findOne({ _id: new ObjectId(id) });
}

export async function addRating(id, stars) {
  const result = await db.collection("dishes").updateOne(
    { _id: new ObjectId(id) },
    { $push: { ratings: stars } },
  );
  return result.matchedCount === 1;
}

export async function topDishes() {
  return db.collection("dishes").aggregate([
    { $addFields: { avg: { $avg: "$ratings" } } },
    { $sort: { avg: -1 } },
    { $limit: 5 },
  ]).toArray();
}
  • Never build filters from raw request bodies — { email: req.body.email } where email is { "$ne": null } matches everyone (NoSQL injection). Validate types first.
  • Keep the connection string in an environment variable.
  • Mongoose wraps this with schemas and models; Prisma also supports MongoDB.

The rest of this lesson

  • One client for the whole appexplain
  • ObjectIds from URLsexplain
  • Injection?predict
  • Safe or unsafe?match
  • String vs ObjectIdpredict
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB