MongoDB Interactions with Mongoose in Node.js

MongoDB Interactions with Mongoose in Node.js

ยท

3 min read

Introduction: MongoDB has become a popular choice for developers due to its schema-less nature and powerful querying capabilities. However, interacting directly with MongoDB from Node.js can sometimes be difficult to handle, especially when dealing with complex data structures and relationships. This is where Mongoose, an object data modelling (ODM) library for MongoDB and Node.js, comes into play. In this article, we'll explore how Mongoose simplifies MongoDB interactions in Node.js applications with code examples.

What is Mongoose? Mongoose is an ODM library for MongoDB and Node.js, providing a schema-based solution for modelling application data. It allows developers to define schemas, which represent the structure of the data, including properties, types, validation rules, and relationships. Mongoose provides an easy to understand API for performing CRUD (Create, Read, Update, Delete) operations, data validation, middleware hooks, and more.

๐Ÿค Getting Started with Mongoose**:** To begin using Mongoose in your Node.js application, first, install it via npm:

npm install mongoose

Then, require it in your Node.js script:

const mongoose = require('mongoose');

Next, connect to your MongoDB database:

mongoose.connect('mongodb://localhost:27017/my_database').then(() => {
  console.log('Connected to MongoDB');
}).catch((error) => {
  console.error('Error connecting to MongoDB:', error);
});

๐Ÿค Defining Schemas and Models: Let's define a simple schema for a "User" model:

const { Schema } = mongoose;

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

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

In this schema:

  • We define properties like "username", "email", and "age" along with their types and validation rules.

  • The "createdAt" field is automatically assigned the current date when a new document is created.

๐Ÿค CRUD Operations with Mongoose**:** Now, let's perform CRUD operations using the "User" model we just defined:

  1. Create:
const newUser = new User({
  username: 'Bahaa_kamal',
  email: 'Bahaa@example.com',
  age: 23
});

newUser.save()
  .then(user => {
    console.log('User created:', user);
  })
  .catch(error => {
    console.error('Error creating user:', error);
  });
  1. Read:
User.find({ age: { $gte: 20 }})
  .then(users => {
    console.log('Users with age >= 20 :', users);
  })
  .catch(error => {
    console.error('Error fetching users:', error);
  });
  1. Update:
User.updateOne({ username: 'Bahaa_kamal'}, { age: 35 })
  .then(result => {
    console.log('User updated:', result);
  })
  .catch(error => {
    console.error('Error updating user:', error);
  });
  1. Delete:
User.deleteOne({ username: 'Bahaa_kamal' })
  .then(result => {
    console.log('User deleted:', result);
  })
  .catch(error => {
    console.error('Error deleting user:', error);
  });

๐Ÿค Key Features of Mongoose:

  1. Schema Definition: Define the structure of MongoDB documents using schemas.

  2. Model Creation: Create constructor functions for interacting with MongoDB collections.

  3. Validation: Ensure data consistency by defining validation rules within schemas.

  4. Middleware: Execute custom logic at various document lifecycle stages.

  5. Query Building: Simplify data retrieval with a powerful query builder API.

  6. Population: Reference and retrieve related documents easily.

  7. Plugins: Extend functionality with reusable modules.

๐Ÿค Conclusion:

Mongoose offers a strong and intuitive way to work with MongoDB in Node.js applications. Its schema-based approach, and features like validation, middleware, and query building, simplifies database interactions and enhances developer productivity.

ย