How to Install and Use Mongoose With Node.js for MongoDB

Alper Tellioglu
The Startup
Published in
6 min readOct 30, 2020

--

use mongoose with node.js to make things easier for MongoDB

First of all you should have installed MongoDB and be able to run it before you install mongoose. You can read this article to see how to do that on Mac.

In order to install mongoose, we’ll use npm command in the project folder. But first, you should go to the relevant project folder in command line.

Hint: You can use cd command to change directories in command line. (ex: cd Desktop)

  1. Install mongoose with npm
npm i mongoose

Once that’s done, we can go over to the next step which is requiring mongoose in our project. Whether you use Atom, VScode or any other IDE, go to the actual javascript file which is usually called as app.js. Then assign mongoose constant with require.

2. Require mongoose in app.js

const mongoose = require("mongoose");

Then, we should connect mongoose with MongoDB.

3. Connect to MongoDB

mongoose.connect("mongodb://localhost:27017/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 app.js). If you got any deprecation warning, you can pass the recommendation as a parameter to connect function.

4. Handle Deprecation Warnings

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

Before inserting any document into database, we should first create a schema which explains the structure of the documents to the system. A schema should look like this.

5. Create Schema

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.

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

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

8. Save the Document

dog.save();

Be careful with this code line. If you call it publicly inside your app.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.

9. Check DB

#go to the command line
#be sure mongoDB is running
mongo
#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
>db.dogs.find()
# now we should see the documents in dogs collection, we have one:
# {name: "Rex", age: 1, breed: "Golden Retriever"}

10. insertMany( ) in Mongoose

Dog.insertMany([dog1, dog2, dog3], function(err{});

After that you created the collection, whenever you want to insert more than one item into there, you can call insertMany( ) function. Note that dog1, dog2, and dog3 are Dog object and assume they are created with rules of dogSchema. So yes, we can pass an array as a parameter in insertMany( ).

Up until now, we were using find( ) method in mongo shell to retrieve documents. What if we want to have them in our code? Say we need to filter some documents, play with them, and update them. To achieve this, we can use find( ) method in app.js as well. Syntax will be a bit different than the previous one. Check below.

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

12. Validation in Mongoose

const dogSchema = new mongoose.Schema({
name {
type: String,
required: true
},

age: Number,
breed: String
});

If you want to restrict the fields of the documents like the example above, you can do that by specifying it into the schema. By setting required attribute as true, we no longer allow dogs without a name. We could be more specific. For instance we could put a min and max value for age attribute.

13. Min-Max Validation

const dogSchema = new mongoose.Schema({
name {
type: String,
required: true
},
age {
type: Number,
min: 1,
max: 20
},

breed: String
});

Let’s continue with update operations. We will see updateOne( ) method for the simplicity, you may use updateMany( ) as well.

Now, remember when we created the dogSchema, we didn’t give any id to the documents. In this case, _id parameter auto-generated by mongoose. Go to the command line and run db.dogs.find( ) method. You will se a default id next to documents, something like this: “5f9c2d128f5033d1b0e7861c”. We will use this id to reach a unique document.

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

15. 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 documents.

16. Delete All

Dog.deleteMany({}, function(err){});
  • This code would delete all of the documents in dogs collection since the query section is empty.

Establishing Relationships in Mongoose

You should specify the relations in the schema before you create the objects. Below, you can see the code example of 2 different schemas with a relationship.

#Two Schemas: Person and Carconst personSchema = new mongoose.Schema({
name: String,
age: Number,
car: carSchema
});
const carSchema = new mongoose.Schema({
brand: String,
model: Number,
color: String
});
#Two Documents(objects)const car1 = new Car({
brand: "Toyota",
model: 2020,
color: "White"
});
const person1 = new Person({
name: "Alex",
age: 23,
car: car1
});
# car attribute of person1 is car1
# that is the relationship between collections

Let’s assume someone in our database used to has no car but bought a new one. We should update the car field of that person in our database.

If you want to create relationship with already existing document: use update function.

Person.updateOne({name: "Beth"}, {car: carX}, function(err){});
  • Beth was already in the database but she didn't have a car. Now she has.

Thanks for reading,

Take care,

--

--