Node.js MongoDB with Mongoose

Node.js MongoDB with Mongoose

Section (3.10) – Node.js MongoDB with Mongoose

When building a Node.js application with MongoDB, using an Object-Document Mapping (ODM) library like Mongoose can greatly simplify and streamline the development process. In this tutorial, we will explore what Mongoose is and how it can be used to define models and associations, perform CRUD operations, and validate data in MongoDB.

What is Mongoose?

Mongoose is a JavaScript library that provides a schema-based solution for working with MongoDB. It allows developers to define models, associations, and validation rules for MongoDB documents, as well as perform CRUD operations and handle middleware functions.

Installing and Configuring Mongoose

To get started with Mongoose, we first need to install it using NPM. We can do this by running the following command in our terminal:

npm install mongoose

Once Mongoose is installed, we can require it in our Node.js application and connect it to our MongoDB database using the mongoose.connect() method. This method takes a MongoDB connection string as its argument, which specifies the location of our MongoDB database.

Defining Models and Associations

With Mongoose, we can define models and associations for our MongoDB documents using a schema-based approach. To define a model, we first need to create a schema object that specifies the properties and types of our MongoDB document. We can do this using the mongoose.Schema() method. For example:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  posts: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Post'
    }
  ]
});

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

module.exports = User;

In this example, we have defined a user schema that includes the properties name, email, password, and posts. The name and email properties are required, and the email property is also set to be unique. The posts property is an array of ObjectIds that reference the Post model.

CRUD Operations with Mongoose

Mongoose provides a set of methods that can be used to perform CRUD operations on our MongoDB documents. Some commonly used methods include:

  • Model.create(): creates a new document
  • Model.find(): retrieves documents that match a given query
  • Model.findOne(): retrieves the first document that matches a given query
  • Model.updateOne(): updates the first document that matches a given query
  • Model.deleteOne(): deletes the first document that matches a given query

Creating Documents

To create a new document in MongoDB using Mongoose, we first need to define a model for our collection. A model is a blueprint that defines the structure of the documents in a collection.

To define a model, we use the Schema class provided by Mongoose. Here’s an example:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: String,
  email: String,
  age: Number
});

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

In this example, we define a userSchema with three fields: name, email, and age. We then create a model named “User” using the mongoose.model() method.

To create a new document, we can simply create a new instance of the User model and call the save() method:

const newUser = new User({
  name: 'John Doe',
  email: 'john.doe@example.com',
  age: 30
});

newUser.save()
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.error(err);
  });

In this example, we create a new User instance with the name, email, and age fields, and then call the save() method to save the document to the database. The save() method returns a Promise, which we can handle using the then() and catch() methods.

Reading Documents

To read documents from a MongoDB collection using Mongoose, we can use the find() method provided by the model. Here’s an example:

User.find()
  .then(users => {
    console.log(users);
  })
  .catch(err => {
    console.error(err);
  });

In this example, we use the find() method to retrieve all documents from the User collection. The find() method returns a Promise that resolves to an array of documents.

We can also use the findOne() method to retrieve a single document from the collection:

User.findOne({ name: 'John Doe' })
  .then(user => {
    console.log(user);
  })
  .catch(err => {
    console.error(err);
  });

In this example, we use the findOne() method to retrieve a single document where the name field is equal to ‘John Doe’.

Updating Documents

To update documents in a MongoDB collection using Mongoose, we can use the updateOne() or updateMany() method provided by the model. Here’s an example:

User.updateOne({ name: 'John Doe' }, { age: 35 })
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.error(err);
  });

In this example, we use the updateOne() method to update a single document where the name field is equal to ‘John Doe’. We pass an object with the new field values as the second argument to the method.

Deleting Documents

To delete a document from our MongoDB database using Mongoose, we can use the findOneAndDelete() method:

UserModel.findOneAndDelete({ _id: '123456789012345678901234' })
  .then(() => console.log('User deleted successfully'))
  .catch(err => console.error(err));

In this example, we are deleting a user with the ID ‘123456789012345678901234’.

Validating Data Mongoose also provides built-in validation for data. We can define validation rules for our models using the validate() method:

const UserSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  }
});

const UserModel = mongoose.model('User', UserSchema);

const user = new UserModel({
  firstName: 'John',
  lastName: 'Doe',
  email: 'john.doe@email.com'
});

user.validate()
  .then(() => console.log('User data is valid'))
  .catch(err => console.error(err));

In this example, we are validating that the required fields (firstName, lastName, email, and password) are present.

Conclusion

Mongoose is a powerful library that makes working with MongoDB in Node.js applications easy and efficient. By defining models and using Mongoose’s built-in methods, we can perform CRUD operations, validate data, and manage associations with ease.