NodeJS: Data Persistence with MongoDB and Mongoose

Introduction:

When building RESTful APIs, data persistence is a vital aspect. MongoDB is a popular NoSQL database that works well with Node.js and Express. In this section, we will explore how to integrate MongoDB into your Node.js application using the Mongoose ODM (Object Data Modeling). We will cover topics such as connecting to MongoDB, defining schemas and models, performing CRUD operations, and handling data validation.

Connecting to MongoDB:

  1. Install the mongoose package by running the following command in your terminal or command prompt:

     npm install mongoose
    
  2. Import the mongoose module and connect to your MongoDB database using the following code:

     const mongoose = require('mongoose');
     mongoose.connect('mongodb://localhost/my-database', {
       useNewUrlParser: true,
       useUnifiedTopology: true,
     })
       .then(() => {
         console.log('Connected to MongoDB');
       })
       .catch((error) => {
         console.error('Failed to connect to MongoDB:', error);
       });
    

    Replace 'mongodb://localhost/my-database' with the appropriate MongoDB connection URL for your database.

Defining Schemas and Models:

  1. Define a Mongoose schema to structure the data stored in MongoDB. For example, to define a User schema with name and email fields, use the following code:

     const mongoose = require('mongoose');
    
     const userSchema = new mongoose.Schema({
       name: {
         type: String,
         required: true,
       },
       email: {
         type: String,
         required: true,
         unique: true,
       },
     });
    
     const User = mongoose.model('User', userSchema);
    

    This code defines a schema with the required name and email fields.

Performing CRUD Operations:

  1. Creating a new document (user) in the database:

     const user = new User({
       name: 'John Doe',
       email: 'john@example.com',
     });
    
     user.save()
       .then((savedUser) => {
         console.log('User created:', savedUser);
       })
       .catch((error) => {
         console.error('Failed to create user:', error);
       });
    
  2. Retrieving documents from the database:

     User.find()
       .then((users) => {
         console.log('Users:', users);
       })
       .catch((error) => {
         console.error('Failed to retrieve users:', error);
       });
    
  3. Updating a document:

     User.findByIdAndUpdate(userId, { name: 'Updated Name' })
       .then((updatedUser) => {
         console.log('User updated:', updatedUser);
       })
       .catch((error) => {
         console.error('Failed to update user:', error);
       });
    
  4. Deleting a document:

     User.findByIdAndDelete(userId)
       .then(() => {
         console.log('User deleted');
       })
       .catch((error) => {
         console.error('Failed to delete user:', error);
       });
    

Data Validation with Mongoose:

  1. Add validation rules to your schema fields. For example, to validate the email format and enforce a minimum length for the name field, modify the schema as follows:

     const userSchema = new mongoose.Schema({
       name: {
         type: String,
         required: true,
         minlength: 3,
       },
       email: {
         type: String,
         required: true,
         unique: true,
         validate: {
           validator: (value) => {
             // Custom email validation logic
             return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
           },
           message: 'Invalid email format',
         },
       },
     });
    

    This code adds validation rules to the name and email fields.

Conclusion: Integrating MongoDB with Mongoose into your Node.js application allows you to store and retrieve data easily. By connecting to MongoDB, defining schemas and models, performing CRUD operations, and implementing data validation with Mongoose, you can create robust and reliable RESTful APIs with persistent data storage. MongoDB's flexibility and Mongoose's powerful features simplify database operations, enabling you to focus on developing the core functionality of your API.

Did you find this article valuable?

Support Oluwatosin Gbenga by becoming a sponsor. Any amount is appreciated!