Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Mongoose is a powerful Node.js Object Data Modeling(ODM) module that provides MongoDB functionality to your Express app. In this post, we will look into Mongoose and see how it can be used with MongoDB through a demonstration. We will learn how to use MongoDB to create, edit, remove and read documents.
MongoDB: What is it?
Before we jump into what Mongoose is, let's have an understanding of what MongoDB is. MongoDB is a document-oriented NoSQL database that is primarily used for large-scale data storage.MongoDB leverages collections and documents rather than tables and rows as in traditional relational databases. A typical document structure in MongoDB would look something like this:
One of the most critical aspects of MongoDB is its architectural flexibility. Consider the example above, even though the Company object contains name, URL, and courses, properties are not required in every Company document part of the Company collection. This is what distinguishes MongoDB from SQL databases such as MySQL or Oracle SQL, which need a fully defined database schema for each item it contains. Here's where Mongoose comes into play; it leverages this very ability of MongoDB to build dynamic objects that are saved in the database as documents.
Mongoose: An introduction
The relation between Mongoose and MongoDB is analogous to the one between Node and express. Express is an abstraction layer over Node.js, whereas Mongoose is an abstraction layer over the standard MongoDB driver. And, in essence, an object data modeling library provides a method for us to develop JavaScript code that interacts with the database. We choose Mongoose over other MongoDB drivers because of its out-of-the-box functionality, which helps us construct our apps more quickly and easily.
Getting Started
Installation
Create a new project and use the command npm init to get it up and running.
npm init
Type in the below command to install mongoose. The 5 corresponds to the version we are going to use.
npm install mongoose@5
Connection
Let’s establish a connection between Mongoose and our MongoDB database.
Include the following code in a new file named server.js
If you don’t prefer using promises, you can use async-await here too. Finally, run node server.js to run the app. We’ve successfully connected Mongoose to our Database!
Mongoose Schema vs. Model: A comparison
In Mongoose, a schema is where we specify the data's structure, default values, constraints, and validation. A Mongoose model serves as a wrapper on this schema. It offers a database interface for generating, querying, updating, and removing records, among other things. Creating a Mongoose model consists primarily of three steps:
Referencing Mongoose
let mongoose = require('mongoose')
Defining our Schema
A schema describes document properties using an object, where the key name matches the collection's property name.
let nameSchema = new mongoose.Schema( { name: String })
Here, we define a property named name with the schema type String, which translates to an internal validator that will be triggered when the model is saved to the database. It will fail if the value's data type is not a string.
Exporting a Model
We must invoke the model on the Mongoose instance and pass the name of the collection as well as a reference to the schema specification.
We can use the following syntax to construct an instance of the model we described earlier and populate it:
let nameModel = require('./name')
let firstName = new nameModel({ name: 'Ninja' })
Create Documents
Let's work on the nameModel from earlier to create a new Document. It is very similar to creating objects in Javascript. Let's say we have to add a new name-" Alex" and save it as a document; this is how we'd do it:
const trial = new nameModel({ name: "Alex", });
This document is then created and stored in trial, but this hasn’t been saved yet.To save the document, the save() method is used.
The _id field is auto-generated and serves as the collection's main key. Its value is the document's unique identification.
Value of the name field is returned
__v is the versionKey attribute Mongoose assigns to each document when generated for the first time. Its value includes the document's internal revision.
Read Documents
To read documents from a collection, we have the find() function. We use all of the methods directly on the model object to read documents.
Let’s say we had to find the record we just created earlier; we can use the find method and pass the name as an object.
To update a document, we utilise the model object's findByIdAndUpdate() function. The _id, MongoDB itself generates, is sent as a parameter to the method. Let's change the name from "Alex" to "Bruce" in the document we created earlier. Since this method doesn't return the document, you'll need to use the find function as discussed above to see the changes in the document.
It is relatively simple to delete a document using Mongoose. We call the findByIdAndDelete function, passing the id of the document to be removed as an argument. Let’s delete our document.
What is the difference between Mongoose and MongoDB? MongoDB is the native Node.js driver for communicating with a MongoDB instance, while Mongoose is an Object modeling tool for MongoDB. Mongoose is developed on top of the MongoDB driver to provide programmers with a means to model their data.
Should you create a new connection for each database operation? No. When your application starts up, connect to it and leave it open until the app closes.
Key Takeaways
In this article, we’ve just covered the basic functionality offered by Mongoose. Technically, the use of Mongoose is optional; you can interact with MongoDB using the Mongo Driver. But using mongoose is the preferred option among developers, as it simplifies the process. If you want to learn advanced web development, Coding Ninjas has one of the best courses available, which you can find here.