Topics Databases & ORMs MongoDB with Mongoose
intermediate 18 min read

MongoDB with Mongoose

Model data, perform CRUD operations, and use Mongoose ODM with MongoDB.

Mongoose ODM

const mongoose = require('mongoose');\n\n// Connect\nawait mongoose.connect('mongodb://localhost:27017/myapp', {\n  useNewUrlParser: true,\n  useUnifiedTopology: true,\n});\n\n// Define schema\nconst userSchema = new mongoose.Schema({\n  name: { type: String, required: true, trim: true },\n  email: { type: String, required: true, unique: true, lowercase: true },\n  age: { type: Number, min: 0, max: 150 },\n  role: { type: String, enum: ['user', 'admin'], default: 'user' },\n  createdAt: { type: Date, default: Date.now },\n});\n\n// Virtual property\nuserSchema.virtual('isAdult').get(function() {\n  return this.age >= 18;\n});\n\n// Instance method\nuserSchema.methods.toJSON = function() {\n  const obj = this.toObject();\n  delete obj.__v;\n  return obj;\n};\n\n// Model\nconst User = mongoose.model('User', userSchema);\n\n// CRUD\nconst user = await User.create({ name: 'Alice', email: '[email protected]' });\nconst users = await User.find({ age: { $gte: 18 } }).sort({ name: 1 }).limit(10);\nconst updated = await User.findByIdAndUpdate(id, { age: 31 }, { new: true });\nawait User.findByIdAndDelete(id);

Examples

const mongoose = require('mongoose');

// Schema
const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true, min: 0 },
  category: { type: String, index: true },
  tags: [String],
  inStock: { type: Boolean, default: true },
});

productSchema.index({ name: 'text', tags: 'text' });

const Product = mongoose.model('Product', productSchema);

// Queries
const cheap = await Product.find({ price: { $lt: 10 } });
const byCategory = await Product.find({ category: 'electronics' })
  .sort({ price: 1 })
  .limit(20);

// Aggregation
const stats = await Product.aggregate([
  { $group: { _id: '$category', count: { $sum: 1 }, avgPrice: { $avg: '$price' } } },
  { $sort: { count: -1 } },
]);

console.log('Category stats:', stats);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.