MongoDB Atlas for production, Mongoose for Node.js with schemas, validation, and populate.
# 1. Sign up at mongodb.com/atlas (free tier = 512MB)
# 2. Create a cluster (M0 = free)
# 3. Create a database user
# 4. Add your IP to the allowlist
# 5. Get connection string:
# mongodb+srv://user:[email protected]/mydbnpm install mongoose
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGODB_URI);
const postSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true, maxlength: 200 },
body: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
tags: [String],
published: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
});
postSchema.index({ title: 'text' });
export const Post = mongoose.model('Post', postSchema);// Create
const post = await Post.create({
title: 'Hello',
body: 'World',
author: userId
});
// Read with populate (join)
const posts = await Post.find({ published: true })
.populate('author', 'name email') // only name and email
.sort('-createdAt')
.limit(20);
// Update
await Post.findByIdAndUpdate(id, { $set: { published: true } }, { new: true });
// Delete
await Post.findByIdAndDelete(id);populate() performs a join: replaces ObjectId references with the actual documents.ref: 'User' in the schema tells Mongoose which model to use for populate.