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.