Mongoose

SAAD ZAKAULLAH AHMAD
6 min readJul 30, 2020

Mongoose is an ODM(object document mapper) library which allows our Nodejs (which speaks the language of JavaScript objects) apps to interact with mongoDB database which speaks the language of documents, collections and databases.

The main objective of mongoose is to shorten the validation code, the writing of business logic boilerplate and to make the codes shorter and easier to work with.

Using Mongoose

  1. Create a directory called FruitsProject and create a file named app.js in it.
  2. initialise npm from the terminal

npm init -y (for windows OS).

3. To install mongoose, go in your working directory and type

npm i mongoose

in your terminal.

4. Open VS code and type

The first line here requires mongoose and the second line connects to our mongoDB database server at the port 27017 and creates a database named fruitsDB if it is not created.

5. Save this and type

node app.js

in your terminal.

Here we see a deprecation warning

To remove this deprecation warning, type

{ useNewUrlParser: true ,useUnifiedTopology: true}

after /fruitsDB” as shown below:

Note: By the time you are reading this, the method I used in point number 5 to remove deprecation warning may become obsolete. You may get some more warnings or might end up getting no warnings at all. To troubleshoot this, simply copy the warning using Ctrl+Rclick and paste it in google and follow the steps.

Inserting data in our database

  1. Create a new schema. (Schema is the structure of our data that we want to store in our MongoDB database). In this schema, we put a framework for our data.

This lays out the foundation of every fruit document that will be added to our database.

2. Use the schema to create a mongoose model.

The first parameter(which should be a string) is the name of collection that is going to comply with the schema. The mongoose way of doing things is to write this parameter in singular form. The second parameter is the structure or the name of schema to which we want our first parameter to stick to. After writing line number 11 only we have created a new collection called fruits and now and only now we’ll be able to create new document named “fruit”.

3.

Create a new document called “fruit” from the model “Fruit” and which will stick to fruitSchema.

4. Type

to save the fruit document into Fruits collection inside fruitsDB. Note that every single time we run fruit.save(), it will save the same fruit i.e, Apple to our fruits collection in our fruitsDB. To avoid repeatedly saving the same fruit, just comment out the function call fruit.save() after saving it for the first time.

5. Save app.js and run execute the command node app.js in the terminal(Make sure that you are in the working directory and mongod server in running on another tab). To run the mongod server, simply type mongod in another tab in your terminal.

6. In another tab inside the terminal, type mongo

7. type show dbs in mongo shell

We see that fruitsDB is added.

8. Switch to fruitsDB by typing use fruitsDB and then type show collections.

Here, we see that mongoose has automatically added ‘s’ in the last of fruit collection, thereby making it plural.(Mongoose is smart😎)

Creating/Inserting many objects in a document

Now that we have made our fruitSchema, we can insert multiple objects in the collection.

Say, we have to add two new fruits Kiwi and Grapes in our collection.

Line 21 to 31 are self explanatory. To save the object in bulk, tap into the Fruit model and use the insertMany method with it. The first parameter would be of the array of the name of fruits we want to save and the second parameter would be a callback function which allows us to log the errors which occurred during the entry of the objects in our fruits collection.

Accessing the objects in our database through our app

  1. Tap into the Fruit model and call the find function on it. The first parameter would be the error function and the second one would be what we’re getting back i.e, fruits collection. If we get any errors, we log that error or we simply log the name of fruits.

Note: At this point, do comment out insertMany() part if you don’t want to add its contents again and again each time we run app.js .

2. Run app.js

Note that the fruit we get back is an array of the objects each with their own property.

Now we see that we have to close our database connection each time using Ctrl+C (because in app.js, we’ve not closed the connection which was opened at line number 3 above). In order to prevent this from happening, use mongoose.connection.close() as shown below:

NOTE: Line 49–52 is for logging only the fruits name in our app.

Updating data

In the mongo shell, we get a unique id for every item that we’ve entered.

This id can be used to update the items data in future.

For example, if we want to add a name (say, Peach) to one of our items having a specific id in fuitsDB, we’ll use the following commands:

The first parameter in the updateOne() is the unique id of the item to which we want to update something and the next parameter is the property which we want to add (here, name) followed by the err function whose functionality is discussed above.

Deleting data

The process of deleting data is similar to updating it.

Following is the process to delete a record named “Grapes” in the fruitsDB.

Thanks for reading. If you liked the blog, give it a 👏.

--

--

SAAD ZAKAULLAH AHMAD

A web developer, mechanical engineer and an eternal learner.