Node.js + MongoDB
CRUD from Node.js
The same operations as the shell, with cursors, toArray, and error shapes you will actually handle.
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();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;
}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?
Comparing _id to a string instead of ObjectId. Calling toArray() on an unbounded find. Not handling duplicate key 11000. Creating a new MongoClient per call. find() returns a cursor, not an array; findOne returns null on miss.
Practice
Same filters — in the driver they are collection methods.