MongoDB Atlas for production, Mongoose for Node.js with schemas, validation, and populate.
Atlas and Mongoose is one of the most important topics in MongoDB in 5 Days. This lesson builds the foundation you need before moving to more advanced concepts — take time with each example and run the code yourself.
# 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]/mydb
npm 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); Before moving on, make sure you can answer these without looking: