Skip to content
All essays
ArchitectureJanuary 19, 202514 min

MongoDB & Mongoose: Complete NoSQL Database Guide

Master MongoDB and Mongoose ODM. Learn schema design, querying, aggregation, and best practices for NoSQL databases.

Ü
Ümit Uz
Mobile & Full Stack Developer

What is MongoDB?

MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents.

Connecting to MongoDB

javascript
import mongoose from 'mongoose';

await mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

Defining Schemas with Mongoose

javascript
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  age: {
    type: Number,
    min: 0,
    max: 120
  },
  isActive: {
    type: Boolean,
    default: true
  },
  role: {
    type: String,
    enum: ['user', 'admin', 'moderator'],
    default: 'user'
  }
}, {
  timestamps: true
});

const User = mongoose.model('User', userSchema);

CRUD Operations

Create

javascript
const user = await User.create({
  name: 'John Doe',
  email: 'john@example.com',
  age: 30
});

Read

javascript
// Find all
const users = await User.find();

// Find with filter
const activeUsers = await User.find({ isActive: true });

// Find one
const user = await User.findOne({ email: 'john@example.com' });

// Find by ID
const user = await User.findById('userId');

Update

javascript
// Update one
await User.updateOne(
  { _id: userId },
  { name: 'Jane Doe' }
);

// Find and update
const user = await User.findByIdAndUpdate(
  userId,
  { age: 31 },
  { new: true }
);

Delete

javascript
await User.findByIdAndDelete(userId);

Query Operators

javascript
// Comparison
await User.find({ age: { $gte: 18, $lte: 65 } });

// Logical
await User.find({
  $or: [
    { role: 'admin' },
    { age: { $gte: 21 } }
  ]
});

// Array operations
await User.find({ tags: { $in: ['javascript', 'nodejs'] } });

Aggregation

javascript
const result = await User.aggregate([
  { $match: { isActive: true } },
  { $group: { _id: '$role', count: { $sum: 1 } } },
  { $sort: { count: -1 } }
]);

Best Practices

  1. 1Use indexes: Speed up queries
  2. 2Validate data: Use schema validation
  3. 3Use lean(): For read-only operations
  4. 4Handle errors: Always use try/catch
  5. 5Use transactions: For multi-document operations

Conclusion

MongoDB with Mongoose provides a powerful, flexible solution for NoSQL data storage.

Related essays

Next essay
GraphQL API Development Guide: Modern API Architecture