How to Use Mongoose in Express Applications
Managing data in a MongoDB database can be challenging, especially when dealing with complex data models. MongoDB is a schema-less database, meaning data can be added without following a particular structure. This flexibility makes MongoDB ideal for storing large amounts of data but also makes managing data more difficult.
Mongoose provides a schema-based solution that helps ensure that data saved to MongoDB is consistent and correctly formatted. With Mongoose, you can define a schema for your data models, which specifies the structure of the data and the rules for how that data should be formatted. Here you will explore how to use Mongoose in an Express application.
MAKEUSEOF VIDEO OF THE DAY
SCROLL TO CONTINUE WITH CONTENT
Nội Dung Chính
Setting Up Your Development Environment
Before using Mongoose, you must install it as a dependency in your project.
You can install Mongoose by running the command below:
npm install mongoose
After you install Mongoose in your project, you need to connect your application to MongoDB using Mongoose.
Mongoose connects to a MongoDB Database using the connect method, which takes a MongoDB URI as an argument.
Here’s an example:
const
mongoose = require
("mongoose"
)
mongoose.connect("mongodb://127.0.0.1:27017/example"
, () =>
console
.log("Connected to database successfully"
)
);
The code block above connects to a local MongoDB instance and logs a success message when your application successfully connects to MongoDB.
Creating a Mongoose Model
A Mongoose model is a schema-based class in Mongoose that allows you to interact with a MongoDB collection.
A Mongoose schema defines the structure of the documents that you can store in a MongoDB collection and provides an interface for creating, reading, updating, and deleting documents in that collection.
When you define a Mongoose model, you define the schema for the documents in that collection, including the properties, their types, and any validations.
Here’s an example of a Mongoose model for a User collection:
const
mongoose = require
("mongoose"
);
const
userSchema = mongoose.Schema({
name: {
type: String
,
required: [true
, "Name is required"
],
},
email: {
type: String
,
required: true
,
},
age: {
type: Number
,
validate: {
validator: function
(value
) {
return
value > 0
;
},
message: ()
=> "Please enter a valid age"
,
},
},
});
const
User = mongoose.model("User"
, userSchema);
module
.exports = User;
The code block above defines a Mongoose schema with three properties: name, email, and age. Each property has a defined set of rules you have to follow when mapping a value to its specified field. Here’s a breakdown of the rules:
- name: The name property is a string type marked as required, meaning you must map a string to this field. If you leave the field empty or enter a different JavaScript data type, Mongoose throws an error.
- email: The email property is a string type marked as required. It has no other validation rules, but in practice, you should validate if the email is correct. You can validate the email using regex expressions or third-party libraries, such as class-validator.
- age: The age property is a number type with a custom validation rule that checks if the value mapped to the field is greater than zero. If the value does not pass the validation, Mongoose throws an error with the message Please enter a valid age. You can leave this field empty as it is not marked as required.
After defining the schema, the code block creates a Mongoose model called User using mongoose.model() method. This method takes two arguments: the model’s name and the schema to use for the documents.
Finally, the User model is exported to other parts of your application.
Interacting With MongoDB Using Mongoose
With your application connected to a MongoDB database and your model created and accessible to other parts of your application, you can interact with your database using methods provided by Mongoose.
For this tutorial, you will perform CRUD operations on a MongoDB database.
Note: Make sure to import your Mongoose model into any module where you’ll perform the CRUD operations.
For example:
const
User = require
("./userModel"
)
Creating a Document
A document is an instance of a model. There are several ways you can create and save a document to MongoDB using Mongoose.
First, you can create an instance of your model’s class and then call the save method on it.
For example:
let
user = new
User({
name,
email,
age,
});
user
.save()
.then(()
=> {
console
.log("User created successfully"
);
})
.catch((
error
) => {
});
The code block above creates and saves a new User document to your MongoDB database.
You can also save data to your database using the create method. The create method instantiates your model and calls the save method on it. In order words, it combines the two operations of the previously mentioned technique.
For example:
User.create({ name, email, age }, (err, data) => {
if
(err) throw
new
Error
("Internal Server Error"
);
console
.log(`User created successfully:
${data}
`);
});
The code block above creates a new User document with the properties passed as an argument to the create method.
Alternatively, you can save data to your database using the insertMany method. Although this method is only ideal for saving data in batches.
For example:
User.insertMany(
[
{ name, email, age },
{ name_1, email_1, age_1 },
],
(err, result) => {
if
(err) {
} else
{
}
}
);
The code block above creates two new documents in the User collection using the array passed as an argument to the insertMany method.
Reading a Document
You can access all the saved documents in your MongoDB database using Mongoose’s find method.
For example:
User.find({})
.then((
data
) => {
console
.log(data);
})
.catch((
err
) => {
});
The code block above will return all the documents in the User collection.
You can also find all documents that match a particular query by passing a query to the find method.
For example:
User.find({ age
: { $gte
: 18
} })
.then((
data
) => console
.log(data))
.catch((
error
) => console
.log(error));
The code block above will return all the documents with an age value greater than 18 in the User collection.
Alternatively, you can read single records using the findById method and passing a document ID as an argument or using the findOne method and passing a filter as an argument.
For example:
User.findById(id, (error, result) => {
if
(result) console
.log(result);
if
(error) console
.error(error)
});
User.findOne({ email
: }).then((
user
) => {
if
(!user) {
}
});
In the above code block, the findById method returns the document with the matching ID. The findOne method returns the first document having the email [email protected].
Updating a Document
You can update a document on MongoDB with Mongoose using the findByIdAndUpdate method. This method takes an ID and an object with the updated details.
For example:
User.findByIdAndUpdate(id, req.body, (err, doc) => {
if
(doc) {
}
if
(err) {
}
});
The code block above updates the document having an ID matching the provided ID with the provided update object (req.body).
Deleting a Document
You can delete a document on MongoDB with Mongoose using the findByIdAndDelete method. This method takes an ID as an argument and deletes the document with the corresponding ID.
For example:
User.findByIdAndDelete(id, (error, result) => {
if
(result) {
}
if
(error) {
}
});
The code block above deletes a document with the given ID from your MongoDB database.
Using Mongoose in Your Express Applications
This article provided an overview of how you could use Mongoose in your express application. Covering how you can establish a connection to MongoDB, structure and validate data saved to your MongoDB database, and perform simple CRUD operations.
By using Mongoose in your Express applications, you can simplify and streamline the interactions between your application and a MongoDB database.