Next

Mongoose Introduction

  • MongoDB basics cover an introduction to MongoDB, differences between NoSQL and SQL databases, and the installation process to start working with MongoDB.
  • What is Mongoose?


    Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a structured way to define data, validate inputs, and interact with MongoDB using JavaScript objects.

    Why Mongoose is Used:

    • Provides schemas to define data structure

    • Adds validation and data consistency

    • Simplifies CRUD operations

    • Easy integration with Express.js


    Example – Simple Schema & Model:

Mongoose Schema and Model Example

This code defines a simple Mongoose schema to structure user data and creates a model to interact with the MongoDB collection using JavaScript objects.

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number
});

const User = mongoose.model("User", userSchema);
  • Explanation:

    • Schema defines the structure of data

    • Model represents a MongoDB collection

    • Each document follows the schema rules

    Connecting MongoDB with Node

    To use MongoDB inside a Node.js application, Mongoose is used to create a connection between the server and the database.

    Steps to Connect MongoDB

    1. Install mongoose package

    2. Import mongoose in the project

    3. Connect using a MongoDB connection string

    Example – MongoDB Connection using Mongoose

Connecting MongoDB with Node.js Using Mongoose

This example shows how to connect a Node.js application to MongoDB using Mongoose. It uses a MongoDB connection string and configuration options to establish a reliable database connection.

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDatabase", {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
  • Explanation:

    • Connection string specifies database location

    • then() confirms successful connection

    • catch() handles connection errors

Next