Getting Started with MongoDB & Mongoose | MongoDB (2023)

In this article, we’ll learn how Mongoose, a third-party library for MongoDB, can help you to structure and access your data with ease.

What is Mongoose?

Many who learn MongoDB get introduced to it through the very popular library, Mongoose. Mongoose is described as “

elegant MongoDB object modeling for Node.js.

Mongoose is an ODM (Object Data Modeling) library for MongoDB. While you don’t need to use an Object Data Modeling (ODM) or Object Relational Mapping (ORM) tool to have a great experience with MongoDB, some developers prefer them. Many Node.js developers choose to work with Mongoose to help with data modeling, schema enforcement, model validation, and general data manipulation. And Mongoose makes these tasks effortless.

If you want to hear from the maintainer of Mongoose, Val Karpov, give this episode of the MongoDB Podcast a listen!

Why Mongoose?

By default, MongoDB has a flexible data model. This makes MongoDB databases very easy to alter and update in the future. But a lot of developers are accustomed to having rigid schemas.

Mongoose forces a semi-rigid schema from the beginning. With Mongoose, developers must define a Schema and Model.

What is a schema?

A schema defines the structure of your collection documents. A Mongoose schema maps directly to a MongoDB collection.

Getting Started with MongoDB & Mongoose | MongoDB (1)

With schemas, we define each field and its data type. Permitted types are:

  • String

  • Number

  • Date

  • Buffer

  • Boolean

  • Mixed

  • ObjectId

  • Array

  • Decimal128

  • Map

What is a model?

Models take your schema and apply it to each document in its collection.

Models are responsible for all document interactions like creating, reading, updating, and deleting (CRUD).

An important note: the first argument passed to the model should be the singular form of your collection name. Mongoose automatically changes this to the plural form, transforms it to lowercase, and uses that for the database collection name.

Getting Started with MongoDB & Mongoose | MongoDB (2)

In this example,

Blog translates to the blogs collection.

(Video) Getting Started with MongoDB & Mongoose ODM (Object Data Modeling) Library

Environment setup

Let’s set up our environment. I’m going to assume you have Node.js installed already.

We’ll run the following commands from the terminal to get going:

Getting Started with MongoDB & Mongoose | MongoDB (3)

This will create the project directory, initialize, install the packages we need, and open the project in VS Code.

Let’s add a script to our package.json file to run our project. We will also use ES Modules instead of Common JS, so we’ll add the module type as well. This will also allow us to use top-level await.

Connecting to MongoDB

Now we’ll create the index.js file and use Mongoose to connect to MongoDB.

Getting Started with MongoDB & Mongoose | MongoDB (5)

You could connect to a local MongoDB instance, but for this article we are going to use a free MongoDB Atlas cluster. If you don’t already have an account, it's easy to sign up for a free MongoDB Atlas cluster here.

And if you don’t already have a cluster set up, follow our guide to get your cluster created.

After creating your cluster, you should replace the connection string above with your connection string including your username and password.

The connection string that you copy from the MongoDB Atlas dashboard will reference the myFirstDatabase database. Change that to whatever you would like to call your database.

Creating a schema and model

Before we do anything with our connection, we’ll need to create a schema and model.

Ideally, you would create a schema/model file for each schema that is needed. So we’ll create a new folder/file structure: model/Blog.js.

Getting Started with MongoDB & Mongoose | MongoDB (6)

Inserting data // method 1

Now that we have our first model and schema set up, we can start inserting data into our database.

Back in the index.js file, let’s insert a new blog article.

Getting Started with MongoDB & Mongoose | MongoDB (7)

We first need to import the Blog model that we created. Next, we create a new blog object and then use the save() method to insert it into our MongoDB database.

Let’s add a bit more after that to log what is currently in the database. We’ll use the findOne() method for this.

Getting Started with MongoDB & Mongoose | MongoDB (8)

Let’s run the code!

(Video) Mongoose Crash Course - Beginner Through Advanced

Getting Started with MongoDB & Mongoose | MongoDB (9)

You should see the document inserted logged in your terminal.

Because we are using nodemon in this project, every time you save a file, the code will run again. If you want to insert a bunch of articles, just keep saving. 😄

Inserting data // method 2

In the previous example, we used the save() Mongoose method to insert the document into our database. This requires two actions: instantiating the object, and then saving it.

Alternatively, we can do this in one action using the Mongoose create() method.

Getting Started with MongoDB & Mongoose | MongoDB (10)

This method is much better! Not only can we insert our document, but we also get returned the document along with its _id when we console log it.

Update data

Mongoose makes updating data very convenient too. Expanding on the previous example, let’s change the title of our article.

Getting Started with MongoDB & Mongoose | MongoDB (11)

We can directly edit the local object, and then use the save() method to write the update back to the database. I don’t think it can get much easier than that!

Finding data

Let’s make sure we are updating the correct document. We’ll use a special Mongoose method, findById(), to get our document by its ObjectId.

Getting Started with MongoDB & Mongoose | MongoDB (12)

Notice that we use the exec() Mongoose function. This is technically optional and returns a promise. In my experience, it’s better to use this function since it will prevent some head-scratching issues. If you want to read more about it, check out this note in the Mongoose docs about promises.

There are many query options in Mongoose. View the full list of queries.

Projecting document fields

Just like with the standard MongoDB Node.js driver, we can project only the fields that we need. Let’s only get the title, slug, and content fields.

Getting Started with MongoDB & Mongoose | MongoDB (13)

The second parameter can be of type Object|String|Array<String> to specify which fields we would like to project. In this case, we used a String.

Deleting data

Just like in the standard MongoDB Node.js driver, we have the deleteOne() and deleteMany() methods.

Getting Started with MongoDB & Mongoose | MongoDB (14)

Validation

Notice that the documents we have inserted so far have not contained an author, dates, or comments. So far, we have defined what the structure of our document should look like, but we have not defined which fields are actually required. At this point any field can be omitted.

(Video) Intro to MongoDB and Mongoose | Node.js Tutorials for Beginners

Let’s set some required fields in our Blog.js schema.

Getting Started with MongoDB & Mongoose | MongoDB (15)

When including validation on a field, we pass an object as its value.

value: String is the same as value: {type: String}.

There are several validation methods that can be used.

We can set required to true on any fields we would like to be required.

For the slug, we want the string to always be in lowercase. For this, we can set lowercase to true. This will take the slug input and convert it to lowercase before saving the document to the database.

For our created date, we can set the default buy using an arrow function. We also want this date to be impossible to change later. We can do that by setting immutable to true.

Validators only run on the create or save methods.

Other useful methods

Mongoose uses many standard MongoDB methods plus introduces many extra helper methods that are abstracted from regular MongoDB methods. Next, we’ll go over just a few of them.

exists()

The exists() method returns either null or the ObjectId of a document that matches the provided query.

Getting Started with MongoDB & Mongoose | MongoDB (16)

where()

Mongoose also has its own style of querying data. The where() method allows us to chain and build queries.

Getting Started with MongoDB & Mongoose | MongoDB (17)

Either of these methods work. Use whichever seems more natural to you.

You can also chain multiple where() methods to include even the most complicated query.

select()

To include projection when using the where() method, chain the select() method after your query.

Getting Started with MongoDB & Mongoose | MongoDB (18)

Multiple schemas

It's important to understand your options when modeling data.

If you’re coming from a relational database background, you’ll be used to having separate tables for all of your related data.

Generally, in MongoDB, data that is accessed together should be stored together.

You should plan this out ahead of time if possible. Nest data within the same schema when it makes sense.

If you have the need for separate schemas, Mongoose makes it a breeze.

(Video) MongoDB Full Tutorial w/ Node.js, Express, & Mongoose

Let’s create another schema so that we can see how multiple schemas can be used together.

We’ll create a new file, User.js, in the model folder.

Getting Started with MongoDB & Mongoose | MongoDB (19)

For the email, we are using a new property, minLength, to require a minimum character length for this string.

Now we’ll reference this new user model in our blog schema for the author and comments.user.

Getting Started with MongoDB & Mongoose | MongoDB (20)

Here, we set the author and comments.user to SchemaTypes.ObjectId and added a ref, or reference, to the user model.

This will allow us to “join” our data a bit later.

And don’t forget to destructure SchemaTypes from mongoose at the top of the file.

Lastly, let’s update the index.js file. We’ll need to import our new user model, create a new user, and create a new article with the new user’s _id.

Getting Started with MongoDB & Mongoose | MongoDB (21)

Notice now that there is a users collection along with the blogs collection in the MongoDB database.

You’ll now see only the user _id in the author field. So, how do we get all of the info for the author along with the article?

We can use the populate() Mongoose method.

Getting Started with MongoDB & Mongoose | MongoDB (22)

Now the data for the author is populated, or “joined,” into the article data. Mongoose actually uses the MongoDB $lookup method behind the scenes.

Middleware

In Mongoose, middleware are functions that run before and/or during the execution of asynchronous functions at the schema level.

Here’s an example. Let’s update the updated date every time an article is saved or updated. We’ll add this to our Blog.js model.

Getting Started with MongoDB & Mongoose | MongoDB (23)

Then in the index.js file, we’ll find an article, update the title, and then save it.

Getting Started with MongoDB & Mongoose | MongoDB (24)

Notice that we now have an updated date!

Besides pre(), there is also a post() mongoose middleware function.

Next steps

I think our example here could use another schema for the comments. Try creating that schema and testing it by adding a few users and comments.

There are many other great Mongoose helper methods that are not covered here. Be sure to check out the official documentation for references and more examples.

Conclusion

I think it’s great that developers have many options for connecting and manipulating data in MongoDB. Whether you prefer Mongoose or the standard MongoDB drivers, in the end, it’s all about the data and what’s best for your application and use case.

I can see why Mongoose appeals to many developers and I think I’ll use it more in the future.

(Video) Build A REST API With Node.js, Express, & MongoDB - Quick

FAQs

How to use MongoDB with mongoose? ›

You can connect to MongoDB with the mongoose.connect() method. mongoose.connect('mongodb://127.0.0.1:27017/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, try using 127.0.0.1 instead of localhost .

Should I use mongoose or MongoDB? ›

Mongoose allows users to conveniently create and manage data in MongoDB. While it is possible to manage data, define schemas, etc. using MongoDB APIs, it is quite difficult to do so. Hence, Mongoose has made lives easier.

Is mongoose easy to learn? ›

Besides, mongoose is also more difficult to learn than the native mongoDB nodeJS driver. This is the question mongoose developers must answer.

Is Mongoose still popular? ›

Mongoose is an incredibly popular and well-done library in the NPM universe. It is used extensively by many excellent programmers based upon its Model-Schema structure.

What is difference between MongoDB and mongoose? ›

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. MongoDB is a schema-less NoSQL document database.

Do companies use Mongoose? ›

197 companies reportedly use Mongoose in their tech stacks, including Accenture, Stack, and platform-stack.

Is Mongoose used in industry? ›

Mongoose is a modern library and is widely used in the industry. Reportedly there are more than 183 companies using mongoose in their tech stack. Popular companies using mongoose as their tech stack are Stack, Accenture, Scale, PedidosYa, Wunderflats, Winds, and many more.

Can I use MongoDB without Mongoose? ›

Yes, of course, drivers provide many advantages to make our lives easy. But to keep things simple and lightweight we can use only MongoDB for CRUD operation without a mongoose. What about validation? Don't worry, packages like sanitize-html can be used in MongoDB to validate data before storing to a database.

How many days it will take to learn MongoDB? ›

How Long Does it Take to Learn MongoDB? Given that MongoDB is a powerful and detailed database management solution, you will probably need about three weeks to get a good start in it.

Is MongoDB good for beginners? ›

MongoDB is a NoSQL (non-relational) database. There are several types of NoSQL databases, and MongoDB is a document-based NoSQL database that is open source . This MongoDB lesson is meant for beginners, so even if you have no prior understanding of the database, you will be able to grasp it.

Is MongoDB easier than MySQL? ›

MySQL flexibility. This is an easy one, and a hands-down win for MongoDB. The schemaless design of MongoDB documents makes it extremely easy to build and enhance applications over time, without needing to run complex and expensive schema migration processes as you would with a relational database.

What is MongoDB for dummies? ›

MongoDB is a general-purpose document database designed for modern application development and for the cloud. Its scale-out architecture allows you to meet the increasing demand for your system by adding more nodes to share the load.

Do I need to know JavaScript to learn MongoDB? ›

Yes, a basic understanding of JavaScript along with familiarity with OOPS concepts is required. The course's title is: “MongoDB for JavaScript Developers” and the objective of this course is to introduce JavaScript Developers to MongoDB and to Learn the essentials of Node.

How to learn MongoDB from scratch? ›

What you'll learn
  1. Download and install MongoDB.
  2. Modify environment variables.
  3. Start and stop mongoDB server.
  4. Connect to MongoDB using python.
  5. Perform CRUD operations.
  6. Create a database.
  7. Create a collection.
  8. Insert documents.

Is it worth using Mongoose? ›

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application. The downside is that we can only create blog posts and they have to follow the above defined schema.

Should I use Mongoose or MongoDB Reddit? ›

Use pure mongodb. Mongoose doesn't really give you anything worthwhile, and is just a new source of bugs.

What is the difference between MongoDB and PostgreSQL? ›

PostgreSQL is a traditional RDBMS (relational database management system) SQL database, like Oracle and MySQL. PostgreSQL is free. MongoDB is a no-schema, noSQL, JSON database. MongoDB has a free version, but they also have hosted and enterprise paid versions.

Is mongoose faster than MongoDB? ›

Mongoose, a neat ODM library for MongoDB used in Node. js projects, has plenty of useful features that make developers' lives easier. It manages relationships between data, has schema validation, and overall allows coding 3-5 times faster.

Which database is best for NodeJS? ›

“Node. js can only be used with MongoDB (which is the most popular NoSQL database).”

What is a schema in MongoDB? ›

What is a Schema? A schema is a JSON object that defines the the structure and contents of your data. You can use Atlas App Services' BSON schemas, which extend the JSON Schema standard, to define your application's data model and validate documents whenever they're created, changed, or deleted.

Do big companies use MongoDB? ›

We have data on 53,983 companies that use MongoDB. The companies using MongoDB are most often found in United States and in the Information Technology and Services industry. MongoDB is most often used by companies with 10-50 employees and 1M-10M dollars in revenue.

Is Mongoose a middleware? ›

Mongoose is an example of database middleware that includes query, aggregate, model, and document middleware.

Which module is internally used by Mongoose? ›

Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node. js server.

Why are mongoose prohibited in us? ›

The Indian mongoose is easily tamed and is often kept as a pet and a destroyer of household vermin. Imported into the West Indies to kill rats, it destroyed most of the small, ground-living native fauna. Because of their destructiveness, it is illegal to import mongooses into the United States, even for zoos.

What are 3 facts about mongoose? ›

Amazing Facts About the Mongoose

There are a range of different types of mongoose (over 30 species). While most are terrestrial, some are semi-aquatic or arboreal. Some species are nocturnal, while others are diurnal. Mongooses generally have long bodies, with short legs, rounded ears, tapered snouts and long faces.

What is mongoose famous for answer? ›

Mongooses are noted for their audacious attacks on highly venomous snakes such as king cobras. The 33 species belong to 14 genera. The most common and probably best-known are the 10 species of the genus Herpestes, among which are the Egyptian mongoose, or ichneumon (H.

Can I use mongoose and MongoDB together? ›

MongoDB is one of the most widely used No-SQL databases in the developer world today. No-SQL databases allow developers to send and retrieve data as JSON documents, instead of SQL objects. To work with MongoDB in a Node. js app, we can use Mongoose.

How to get data from MongoDB using mongoose? ›

  1. Step 1 – Create Node Express js App. ...
  2. Step 2 – Install express flash ejs body-parser mongoose Modules. ...
  3. Step 3 – Connect App to MongoDB. ...
  4. Step 4 – Create Model. ...
  5. Step 5 – Create Routes. ...
  6. Step 6 – Create HTML Table and Display List. ...
  7. Step 5 – Import Modules in App.js. ...
  8. Step 7 – Start App Server.
Oct 30, 2022

Do I need to install MongoDB to use mongoose? ›

First of all you should have installed MongoDB and be able to run it before you install mongoose.

Why mongoose is used in MongoDB? ›

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application. The downside is that we can only create blog posts and they have to follow the above defined schema.

Is mongoose a SQL or NoSQL? ›

MongoDB is a database based on a non-relational document model. Thus, as a so-called NoSQL database (NoSQL = Not-only-SQL), it differs fundamentally from conventional relational databases such as Oracle, MySQL or the Microsoft SQL Server.

Do companies use mongoose? ›

197 companies reportedly use Mongoose in their tech stacks, including Accenture, Stack, and platform-stack.

Is MongoDB best for Python? ›

MongoDB is a document-oriented database classified as NoSQL. It's become popular throughout the industry in recent years and integrates extremely well with Python. Unlike traditional SQL RDBMSs, MongoDB uses collections of documents instead of tables of rows to organize and store data.

Videos

1. MongoDB In 30 Minutes
(Traversy Media)
2. MongoDB Crash Course
(Web Dev Simplified)
3. Getting started with MongoDB database
(kudvenkat)
4. Getting Started with MongoDB Atlas - A Modern Database!
(MongoDB)
5. MongoDB Tutorial For Beginners | Full Course
(Amigoscode)
6. Getting Started with MongoDB and Rust
(MongoDB)
Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated: 12/09/2022

Views: 6363

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.