Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Introduction to Mongoose
tutorial

Introduction to Mongoose

While the native MongoDB driver works great, many Node.js developers prefer using **Mongoose** – an ODM (Object Document Mapper) that provides a higher-level, schema-based abstraction over MongoDB. It adds structure, validation, and many convenience methods.

What is Mongoose?

Mongoose is an ODM library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and translates between objects in code and their representation in MongoDB.

Think of Mongoose as a helpful assistant that makes sure your data is properly formatted before it goes into MongoDB, and nicely packaged when it comes out.

Why Use Mongoose?
  • Schema Definition: Define the structure of your data with types and constraints.
  • Validation: Automatic validation before saving to database.
  • Middleware: Run code before/after certain operations (e.g., hash password before save).
  • Population: Easy way to reference documents in other collections (like joins).
  • Query Building: Chainable API for building complex queries.

Installation
npm install mongoose

Connecting to MongoDB with Mongoose
require('dotenv').config();
const mongoose = require('mongoose');

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/myapp';

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected with Mongoose'))
.catch(err => console.error('Connection error:', err));

<!-- Optional: handle connection events -->
mongoose.connection.on('disconnected', () => {
  console.log('MongoDB disconnected');
});

process.on('SIGINT', async () => {
  await mongoose.connection.close();
  process.exit(0);
});

Basic Schema and Model

In Mongoose, everything starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of documents within that collection.
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  age: { type: Number, min: 0 },
  createdAt: { type: Date, default: Date.now }
});

<!-- Create a model from the schema -->
const User = mongoose.model('User', userSchema);

module.exports = User;

Using the Model
const User = require('./models/User');

<!-- Create and save a new user -->
async function createUser() {
  try {
    const user = new User({
      name: 'Alice',
      email: 'alice@example.com',
      age: 28
    });
   
    const savedUser = await user.save();
    console.log('User saved:', savedUser);
  } catch (err) {
    console.error('Error:', err);
  }
}

createUser();

Two Minute Drill

  • Mongoose is an ODM that provides structure and validation for MongoDB.
  • Install with `npm install mongoose`.
  • Connect using `mongoose.connect()`.
  • Define schemas to specify document structure and validation rules.
  • Create models from schemas to interact with collections.
  • Mongoose handles connection pooling automatically.

Need more clarification?

Drop us an email at career@quipoinfotech.com