Skip to content

Node.js + MongoDB

CRUD from Node.js

The same operations as the shell, with cursors, toArray, and error shapes you will actually handle.

IntermediateAbout 6 minutes

Filters are the same documents as mongosh. The differences that bite in Node: `ObjectId`, cursors, option objects, error codes. CRUD modules taught the operators; this is the driver surface.

import { ObjectId } from "mongodb";

const users = db.collection("users");

await users.findOne({ _id: new ObjectId(req.params.id) });

await users.find({ city: "Bangalore" })
  .project({ name: 1, city: 1 })
  .sort({ name: 1 })
  .limit(20)
  .toArray();
Params are strings. _id in MongoDB is ObjectId.
const ins = await users.insertOne({ name: "Rahul", email: "rahul@example.com" });
// ins.insertedId

const upd = await users.updateOne(
  { _id },
  { $set: { city: "Pune" } }
);
// upd.matchedCount, upd.modifiedCount

try {
  await users.insertOne({ email: "rahul@example.com" });
} catch (err) {
  if (err.code === 11000) { /* unique index — 409 */ }
  throw err;
}
Writes return counts. Duplicate email is 11000, not a generic 500.

find() is a cursor. toArray() pulls the rest into memory — fine for limit(20), fatal for unbounded. Stream with for await (const doc of cursor) when the result is large. findOne is null on a miss, not throw. Driver 6 options can sit in the second argument: find(filter, { projection, sort, limit }). Either style; do not mix skip for deep pages (pagination APIs next).

Interview question

What is easy to get wrong when using the MongoDB Node.js driver?

Think about it first.

Practice

Same filters — in the driver they are collection methods.