MongoDB

The Most Popular Document Database

MongoDB

MongoDB stores JSON-like documents. Flexible schema, easy to start, popular in Node apps.

4 min read Level 2/5 #nodejs#mongodb#nosql
What you'll learn
  • Connect with the official driver
  • Insert and query documents
  • Use Mongoose for schemas

MongoDB is the most-used document database. Each row (“document”) is a JSON-like blob — no fixed schema by default.

Install + Connect

npm install mongodb
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGO_URL);
await client.connect();

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

Insert

const result = await users.insertOne({
  name: "Ada",
  email: "ada@example.com",
  tags: ["admin"],
});
console.log(result.insertedId);   // ObjectId

Query

const one = await users.findOne({ email: "ada@example.com" });

const cursor = users.find({ tags: "admin" }).limit(10).sort({ name: 1 });
for await (const user of cursor) {
  console.log(user);
}

The query is a JSON-like object — same shape as the documents.

Update

await users.updateOne(
  { _id: someId },
  { $set: { email: "new@example.com" }, $push: { tags: "verified" } }
);

Operators like $set, $push, $inc modify specific fields.

Mongoose — Schema Layer

Pure Mongo is schemaless — fine for prototypes, scary at scale. Add a schema layer with Mongoose:

npm install mongoose
import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
  name:  { type: String, required: true },
  email: { type: String, required: true, unique: true },
  tags:  [String],
}, { timestamps: true });

const User = mongoose.model("User", UserSchema);

await mongoose.connect(process.env.MONGO_URL);

const user = await User.create({ name: "Ada", email: "ada@example.com" });
const ada = await User.findOne({ email: "ada@example.com" });

Mongoose adds validation, defaults, hooks (pre("save")), virtuals, and TypeScript types.

When to Pick Mongo

  • Schemas evolve rapidly during product discovery
  • Most reads are by ID, returning a denormalized document
  • Hierarchical data (forums with nested comments) that you don’t want to join

When not to:

  • You have complex relational queries (JOIN everywhere)
  • You need strong transactional guarantees across collections
  • You’re new to it and your team isn’t — Postgres is safer

Hosting

Atlas (cloud MongoDB) has a free tier. Self-hosting is painful — pay for managed.

File Uploads →