Mastering Mongoose An In-Depth Guide with API Examples

Introduction to Mongoose

Mongoose is a powerful and flexible Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward, schema-based solution to model your application data, along with various built-in features to simplify data manipulation and validation.

Getting Started with Mongoose

First, let’s install Mongoose:

npm install mongoose

Then, you can import and connect to your MongoDB instance:

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});

Defining a Schema

Create a model schema to structure your data:

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

Creating a Model

Next, compile the schema into a model:

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

CRUD Operations

Creating Documents

const newUser = new User({ name: 'John Doe', age: 30, email: 'john@example.com' }); newUser.save((err) => {
  if (err) return handleError(err);
  console.log('User saved successfully');
});

Reading Documents

User.find({ name: 'John Doe' }, (err, users) => {
  if (err) return handleError(err);
  console.log(users);
});

Updating Documents

User.updateOne({ name: 'John Doe' }, { age: 35 }, (err, res) => {
  if (err) return handleError(err);
  console.log(res);
});

Deleting Documents

User.deleteOne({ name: 'John Doe' }, (err) => {
  if (err) return handleError(err);
  console.log('User deleted successfully');
});

Advanced Queries

Filtering and Sorting

User.find({ age: { $gt: 18 } }).sort({ age: -1 }).exec((err, users) => {
  if (err) return handleError(err);
  console.log(users);
});

Population

Define multiple schemas for referencing:

const postSchema = new Schema({
  title: String,
  content: String,
  author: { type: Schema.Types.ObjectId, ref: 'User' } 
}); const Post = mongoose.model('Post', postSchema);

Use the populate method to include referenced documents:

Post.find()
  .populate('author')
  .exec((err, posts) => {
    if (err) return handleError(err);
    console.log(posts);
  });

Validation

Add validation rules in your schema:

const userSchema = new Schema({
  name: {
    type: String,
    required: [true, 'Name is required'],
    minlength: [3, 'Name must be at least 3 characters'],
  },
  age: { 
    type: Number,
    min: [18, 'Age must be more than 18 years old'],
    max: [65, 'Age must be below 65 years old']
  },
  email: {
    type: String,
    match: [/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/, 'Please enter a valid email']
  }
});

Plugins

Mongoose plugins add additional functionality to schemas:

 const mongoosePaginate = require('mongoose-paginate-v2'); userSchema.plugin(mongoosePaginate); 

Using pagination:

User.paginate({}, { page: 1, limit: 10 }, (err, result) => {
  if (err) return handleError(err);
  console.log(result);
});

Creating an Express Application with Mongoose

Finally, let’s create a simple Express application:

const express = require('express'); const app = express(); const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: String
});
const User = mongoose.model('User', userSchema);
app.use(express.json());
app.post('/users', (req, res) => {
  const user = new User(req.body);
  user.save()
    .then(() => res.status(201).send(user))
    .catch((err) => res.status(400).send(err));
});
app.get('/users', (req, res) => {
  User.find()
    .then((users) => res.send(users))
    .catch((err) => res.status(500).send(err));
});
app.listen(3000, () => console.log('Server running on port 3000'));  

Now you have a functional RESTful API with Mongoose and Express!

Hash: 4e18123e0f06635b3cab7a620ecf4bbeff385a2f34cecd808dd232fb47b0e655

Leave a Reply

Your email address will not be published. Required fields are marked *