javascript-mongoose

Data Modeling in MongoDB with JavaScript Mongoose

  • 2 min

Mongoose is a JavaScript library that allows us to work with MongoDB in a structured yet fast way, using a schema-based approach.

It provides an elegant solution for modeling our application’s data and performing CRUD (Create, Read, Update, Delete) operations with ease.

Mongoose stands out for the following features:

  • Schema Modeling: Defines the structure of our MongoDB documents through schemas.
  • Validation: Validates data before saving it to the database.
  • Advanced Queries: Performs complex queries easily.
  • Middleware: Uses middleware to perform operations before or after specific events.
  • Plugins: Extends functionality through a wide range of plugins.

Installing Mongoose

To start using Mongoose in our applications, we first need to install it. If we are using npm, we can do so with the following command:

npm install mongoose

How to Use Mongoose

Connecting to MongoDB

First, we need to connect to a MongoDB instance.

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test');
Copied!

Defining Schemas and Models

With Mongoose, we define the structure of our documents through schemas. For example, let’s see how we can define a model to save Users.

const userSchema = new mongoose.Schema({
    name: { type: String, required: true },    
    age: { type: Number, min: 0 }
  });
  
const User = mongoose.model('user', userSchema);
Copied!

That is the normal syntax. But we also have a more concise one, without having to create the Schema.

const Cat = mongoose.model('Cat', { name: String });
Copied!

Creating Documents

To create a new document, we use the model we defined earlier.

const newUser = new User({ name: 'Luis' } );
newUser.save().then(() => console.log('Luis'));
Copied!

Reading Documents

We can read documents from the database using methods like find, findOne, findById, etc.

User.find({ name: 'Luis'})
    .then((items) => console.log(`${items}`));
Copied!

Updating Documents

To update a document, we use methods like updateOne, updateMany, findByIdAndUpdate, etc.

User.updateOne({ name: 'Luis'}, { age: '35'})
    .then((ev) => console.log(ev));
Copied!

Deleting Documents

We can delete documents from the database using methods like deleteOne, deleteMany, findByIdAndDelete, etc.

User.deleteOne({ name: 'Luis'})
  .then(() => console.log('User deleted'))
  .catch((err) => console.log(err));
Copied!