Skip to content

Using Mongoose Module with MongoDB AQSA Spark By {Examples}

  • by

This article is all about the mongoose module of Node.js that is used to work with MongoDB. It provides a higher-level, schema-based interface to work with MongoDB databases, making it easier to manage data and perform CRUD operations.

One of the main advantages of Mongoose is, it allows you to define schemas for your data, which define the structure of your documents and their properties. Besides this, you can also define validation rules, default values, and other options for each property. It also allows us to perform CRUD operations by using the Mongoose API.

In this article, we will work with Mongoose to build Node.js applications that require interaction with MongoDB.

1. Install Mongoose module

The module of mongoose is needed only when you have MongoDB and Node.js are installed and updated within the system. My system already has MongoDB and Node.js installed, hence, I just download and install the Mongoose module by using the npm command.

2. Connect the Mongoose with MongoDB

In the prior section, we successfully got the Mongoose module installed. Now, we built the connection to a MongoDB database using the Mongoose library.

# Connect to a MongoDB database by using Mongoose library
let mongoose = require(‘mongoose’);
const server = ‘127.0.0.1:27017’;
const database = ‘test’;
class Database {
constructor() {
this._connect();
}

_connect() {
mongoose
.connect(`mongodb://${server}/${database}`)
.then(() => {
console.log(‘Database connection successful’);
})
.catch((err) => {
console.error(‘Database connection failed’);
});
}
}
module.exports = new Database();

Here, we first called the mongoose library and assigned to a variable mongoose. After that, we defined the constant server and database which specify the location and name of the database, respectively. Next, we employed the class Database which has a constructor and a _connect() method.

When an instance of this class is established, the constructor invokes the _connect() method to connect to the MongoDB database. Inside the _connect() method, we use Mongoose’s connect() method to build a connection to the MongoDB server using the server and database constants we defined earlier.

In the end, an instance of the Database class is exported using the module.exports statement, which makes it accessible to other parts of the Node.js application that require this module.

Hence, the output shows the message indicating that a connection has been made to the MongoDB database.

3. Create the Model of Mongoose

In the above section, we have significantly connected to the MongoDB server using the Mongoose module. Now, in the next stage, we are going to create the mongoose model. To create a model in Mongoose, we need to define a schema for our data and then use the mongoose.model() method to create the model. Here is an example.

# create the mongoose model
const mongoose = require(‘mongoose’)
const { Schema } = mongoose
const schema = new Schema({
name: String,
age: Number
})
const Student = mongoose.model(‘Student’, schema)

We have defined a Mongoose model for a Student document that is used to store in a MongoDB database. First, the mongoose library is loaded, and the Schema object is destructured from it. Schema is a class in Mongoose that allows us to define the structure of a document, including its fields and their data types.

Then, we have a new schema object which is created using the Schema constructor. The schema defines two fields for a Student document: name, which is a string, and age, which is a number. These fields are defined as key-value pairs in the schema object.

After that, the mongoose.model() method is deployed, which takes two arguments: the name of the model, which is Student, and the schema object that defines the fields of the model.

4. Perform the operations to the Mongoose Model

Note that the creation, updating, and deletion of documents from the MongoDB database are handled by Mongoose models. Here, we have performed some of the basic operations on MongoDl.

First, create the document by using the mongoose model Student generated above.

# Create document by using the mongoose model
Student.create({
name: ‘Timaes’,
price: 22
})
.then(student => console.log(student))
.catch(err => console.error(err))

Here, we retrieved the Student model from Mongoose using the mongoose.model() method, which is defined in the aforementioned section with a schema that specifies the name and age fields. Then, the Student.create() method is called with an object that contains values for the name and age fields of a new Student document.  Thus, the output yielded the document below after execution.

Next, we use the findById() method of mongoose to read the document Student created previously.

# Usage of findById() method
Student.findById(‘645508b209110fc3764f065d’)
.then(student => console.log(student))
.catch(err => console.error(err))

The findById() method is called on the Student model and pass the ID of the document to retrieve its argument. The output is retrieved with the document of the specified ID.

Moreover, we have performed the update operation over the mongoose model Student using the findAndUpdateOne() method.

# Usage of findAndUpdateOne() method
Student.findOneAndUpdate(
{ name: ‘James’ },
{ name: ‘Jimmy’ },
{ new: true })
.then(student => console.log(student))
.catch(err => console.error(err))

The findAndUpdateOne() method first specified the condition name: James to be matched and then specify the update to be applied to the matched document. The document will be changed from James to Jimmy. Finally, for the modified document to be returned, the option new is provided with the value true. The updated document can be seen in the below output.

5. Conclusion

In conclusion, you have learned Mongoose is a Node.js module that is used to interact with MongoDB. We have seen the installation method, connection to MongoDB, creation of the model, and performing some operations using the mongoose methods.

More details about this topic can be found here.

 This article is all about the mongoose module of Node.js that is used to work with MongoDB. It provides a higher-level, schema-based interface to work with MongoDB databases, making it easier to manage data and perform CRUD operations. One of the main advantages of Mongoose is, it allows you to define schemas for your data,  Read More MongoDB, Review 

Leave a Reply

Your email address will not be published. Required fields are marked *