Mongoose for MongoDB | A guide

Pratyksh
Last Updated: May 13, 2022

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:

Company Object

{
name: "Coding Ninjas",
url : " https://www.codingninjas.com",
courses : ["Data structures and Algorithms""Full Stack Node.js"]
}

 

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

// Requiring mongoose
const mongoose = require("mongoose");

// Connecting to Database
const Db = "mongodb://localhost:27017/recipes";

Note: While doing database operations, make sure the mongo shell is running.

mongoose
  .connect(Db, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false
  })
  .then(con => {
    console.log(con.connections);
    console.log(" DB connection successful !");
  });

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.

module.exports = mongoose.model('name', nameSchema)

 

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.

trial.save()
  .then(doc => {
    console.log(doc)
  })
  .catch(err => {
    console.error(err)
  })

 

We get this output, after running the above code.


  _id: 1xt23te3e2f74cr8f81a2019p,
name: 'Alex',
  __v: 0 
}

 

Let’s understand this output better.

  • 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.

const name =nameModel.find(name:”Alex”)
.then(docs => console.log(docs))
.catch(err => console.log("ERROR :", err));

 

The output would be similar to the values we got on creating the document, and it would look something like this.


  _id: 1xt23te3e2f74cr8f81a2019p,
name: 'Alex',
  __v: 0 
}

 

 

 

Update documents

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.

const name = nameModel.findByIdAndUpdate("1xt23te3e2f74cr8f81a2019p", {
name: 'Bruce'
})
.then(doc => console.log(doc))
.catch(err => console.log(err));

 

On using the find function, we’ll get this output:


  _id: 1xt23te3e2f74cr8f81a2019p,
name: 'Bruce',
  __v: 0 
}

 

Delete Documents

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.

const names = nameModel.findByIdAndDelete("1xt23te3e2f74cr8f81a2019p").

 

And voila! Our document has been deleted!

Frequently Asked Questions

  1. 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.
     
  2. 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.

Happy learning!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think