Language: EN

javascript-mongoose

Data Modeling in MongoDB with JavaScript Mongoose

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

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

Mongoose stands out for the following features:

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

To learn more about Mongoose, we can visit the official Mongoose site, check the Mongoose documentation, or explore the repository on GitHub.

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 an instance of MongoDB.

const mongoose = require('mongoose');

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

Defining Schemas and Models

With Mongoose, we define the structure of our documents using 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);

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

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

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'));

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}`));

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));

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));