• 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.
  • Mongoose creates a connection between MongoDB and the Express web application framework

Learning Objectives

  • Set up a database on MongoDB Atlas
  • Create your first collection
  • Create, edit, and delete documents in a MongoDB database using the mongo shell
  • Use the mongo shell.


Mongoose in real project

Now let’s see the steps to use mongoose in a real project.

1. Install mongoose with npm

Let’s go to the project folder and initialize our project if you did not do it yet

npm init -y

Mongoose is installed in your project (package.json) like any other dependency — using NPM. To install it, use the following command inside your project folder

$ npm install mongoose --save
2. Connecting to MongoDB

Mongoose requires a connection to a MongoDB database. but first we need to Require mongoose in our file

// Using Node.js require()
const mongoose = require('mongoose');
// Using ES6 imports
import mongoose from 'mongoose';

Then, we should connect mongoose with MongoDB.

//my_database represent your database name and if it's not exist it will be created 
// In our example we will use dogsDB

The url is default until the last slash. Then you should give your database name. dogsDB is the name of the database in this example. Even if you haven’t one yet, it will create a new database.

Try to run your code in command line(ex: node db.js). If you got any deprecation warning, you can pass the recommendation as a parameter to connect function.

3. Handle Deprecation Warnings
mongoose.connect("mongodb://localhost:27017/dogsDB", {useNewUrlParser: true});

Note: If the local connection fails then try using instead of localhost. Sometimes issues may arise when the local hostname has been changed.

All together

let mongoose = require("mongoose");
//Set up default mongoose connection
let mongoDB = "mongodb://localhost/dogsDB";
async function main() {
  await mongoose.connect(mongoDB, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
main().catch((err) => console.log(err));
4. Create Schema
  • Before inserting any document into the database, we should first create a schema which explains the structure of the documents to the system.
  • A schema defines document properties through an object where the key name corresponds to the property name in the collection.

A schema should look like this.

const dogSchema = new mongoose.Schema({
 name: String,
 age: Number,
 breed: String

Now that we have a schema, we can create a collection. This schema will be the blueprint of the documents into that collection. We will use mongoose.model( ) method in order to create the dogs collection.

5. Create Collection
const Dog = mongoose.model("Dog", dogSchema);

There are some points you should note in the above code line:

  • Firstly, we passed 2 parameters into the function.
    • First one declares the name of the collection. Mongoose automatically convert the first parameter to lowercased plural form to set the collection name. So, the colllection name is “dogs” in this case.

    • Second parameter is the schema of the documents that we want to use for our new collection. By passing dogSchema we declare that, every document in dogs collection are type of dogSchema.

Things will get more clear when we create a new document just below.

6. Create a new Document
const dog = new Dog({
 name: "Rex",
 age: 1,
 breed: "Golden Retriever"

Alright, everything is ready. Only thing left is to save the new dog object into the collection and that is the easiest step.

7. Save the Document;

Be careful with this code line. If you call it publicly inside your db.js file, every time you run your file, this line saves another item into the database. It’s a good idea to comment out that line after running it for the first time. You can also use an if statement if you want a permanent solution.

You can always check the situation of the database to decide whether you accomplished these steps successfully. So. let’s do that.

8. Check DB in terminal

#go to the command line
#be sure mongoDB is running
#now we are in mongo shell
>show dbs
#there must be dogsDB in the list
>use dogsDB
# switched to the dogsDB
>show collecitons
# we should see dogs collection here
# now we should see the documents in dogs collection, we have one:
# {name: "Rex", age: 1, breed: "Golden Retriever"}
9.Find in Mongoose
Dog.find({query}, function(err, foundList){});
  • As a first parameter you can filter the documents with query operators.
  • The second parameter is a callback function which gives you the error if there is any, or gives you the list of the results.
  • So, foundList is the result of the find operation. Since this is a find all function, the result will be an array of items that matches the query.
  • If we left the curly brackets({}) blank as it is, it will return all of the documents. Then, you can play with foundList inside your js file.
10.updateOne( ) Method:
Dog.updateOne({_id: 5f9c2d128f5033d1b0e7861c}, {age: 2}, function(err){});
  • First parameter: this is the query, we are passing an exact id to get that document.
  • Second parameter: the field we want to update, in this case we are updating age of the dog from 1 to 2.
  • Third parameter: this is an error catcher callback function, you can console log the error if you wish.
11.deleteOne( ) Method:
Dog.deleteOne({name: "Rex"}, function(err){});
  • First parameter: this is the query, we are selecting the document we want to delete
  • Second parameter: the default callback function like above.

Note: use **deleteMany( )** in the same way to delete more than one document.


Additional resources