Skip to main content
Course/Module 3/Topic 1 of 3Intermediate

MongoDB with Mongoose

Learn to work with MongoDB using Mongoose ODM for Node.js applications

60 min•By Priygop Team•Last updated: Feb 2026

Introduction to MongoDB

MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js that provides a straightforward schema-based solution for modeling application data.

Setting Up MongoDB with Mongoose

Example
// Install dependencies
npm install mongoose

// Connect to MongoDB
const mongoose = require('mongoose');

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

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
    console.log('Connected to MongoDB');
});

// Define a Schema
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
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// Create a Model
const User = mongoose.model('User', userSchema);

// Using the Model
const newUser = new User({
    name: 'John Doe',
    email: 'john@example.com',
    age: 30
});

newUser.save()
    .then(user => console.log('User saved:', user))
    .catch(err => console.error('Error saving user:', err));

šŸ“š Additional Resources

Recommended Reading

  • • MongoDB Documentation
  • • Mongoose ODM Guide
  • • PostgreSQL Documentation
  • • Sequelize ORM Documentation

Online Resources

  • • MongoDB with Node.js Tutorial
  • • PostgreSQL with Sequelize Guide
  • • Database Design Best Practices
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep