Mongoose is an Object Data Modelling Library(ODM) for MongoDB and Node.js, providing a higher level of abstraction. It is similar to the relationship between Express and Node, as Express is a layer of abstraction over Node.js while Mongoose is a layer of abstraction over the regular MongoDB driver.
And basically, an object data modelling library is simply a way for us to write our JavaScript code that will interact with the database. We use Mongoose over several other MongoDB drivers, because of the out of box functionalities, that allows for faster and simpler development of our applications. Some of the features that Mongoose provides us are schemas to structure and model our data and relationship, easy data validation, simple query APIs and much more.
⭐ Installing Mongoose and Connecting it to our Database
1. Create a new project, and use the command npm init to initialize the project.
a) Create a file called app.js and include the following code –
Here, we
have first created an instance of mongoose and then saved our MongoDb
connection string in the Db object. Make sure that the mongo shell is running,
while you do operations on the database.
b) Connecting to the database -
Include the following code -
Here, mongoose.connect() returns a promise, we have used then here to receive the promise, but
we can also use async-await here.
⭐ Mongoose Schema vs Model
While
Mongo is schema-less, SQL defines a schema via the table definition. A Mongoose
‘schema’ is a document data structure (or shape of the document) that is
enforced via the application layer. In Mongoose, a schema is where we model
our data, where we describe the structure of the data, the default values, the
constraints, and validation.
Now, Mongoose is all about Models and a model is like a blueprint that we use to create, query, update and delete documents. To perform any CRUD operations, we need a Mongoose model, and to create a model, we need a schema.
For instance, let us create a schema for Student. A student will surely have a name, course, and duration.
Here, we have created an instance of the mongoose schema, but it isn't completed yet. We need to pass in the object of the required schema to it.
Note how we have made the name as
required, but the other fields need not be necessarily there except date as default,
if user not enter anything, it will be set as default.
Now, for the required attribute, we can
also pass in the error statement that we want to be displayed when we're
missing the field. We just need to pass an array to the required field, as follows
-
We can also specify default values, for
instance, let's save the default value of our date as Date.now
which will store the current date and time of student admission.
So, this is our very basic schema, and let's now create a model out of it.
📝 Creating Documents -
We use our Student modal to create a new document, just like we create an object using classes in Javascript.
To create a new student with values :
To create this as a document, include the following code -
This creates a new document and stores it to stu1. To save the document, we use the save() method.
save() method also returns a promise when we save the document.
Now, run the app - node app.js, we get the following output in the console.
You may verify that the document is saved, by running db.students.find() in the mongo shell, to see all the documents in the database.
📝 Creating Multiple Documents -
Now, let us try to save multiple documents to the collection -
Now,
let us try to save a document in which name of the student is missing as name
is required field –
Now, if we try to run node app.js, we get the following error -
Now, correct your data and run the command
Student.insertMany() to insert multiple records in the collection. app,
and we get the following output on the terminal -
📝 Reading documents -
We have the find() method to read documents from a collection. To read documents, we use all of the methods directly on the model object.
For instance, to read all documents from the Student model, include the following code:
This gives the following output -
To search for a particular document, we
may specify the required attributes and values and pass it as an object to
the find() method.
For instance, if we want to find the student with course btech', the following code would work -
📝 Updating documents -
To update a document, we need its _id which in our case is automatically created by MongoDB.
To update a document, we use the method findByIdAndUpdate() on the model object. The method takes in the _id as a parameter.
For instance - to update the duration of MCA, include the following code in the program -
Here,
"5d794e71922481309c8e6883" is the id of the document. We can verify
if the document has been updated using db.students.find() in the mongo shell.
We get the following output -
The duration for course of MCA has been successfully updated.
📝 Deleting Documents -
Deleting a document through Mongoose is
very easy. We use the method findByIdAndDelete and pass the id of the document to be deleted as the parameter -
For instance, if we want to delete our first document, include the following code -
This deletes the document with
_id="5d794e71922481309c8e6883". We may verify the delete operation
through our mongo shell.
We get the following results-
The document has been successfully deleted.
And we are all done ! 🎉