i

Connecting to MongoDB

MongoDB is a cross-platform, document-oriented, scalable, high-performance, open-source NoSQL (Not Only SQL) database, and Node has several modules available to connect to it.

Some of the most popular modules are mongoose, mongojs, mongo, etc.

The mongoose is a Node.js module which is used to connect Node.js application with MongoDB database. It provides an elegant MongoDB object modeling for Node.

It manages data relationships and provides validation of schema. It helps in translating the objects in the code with their representation in the database.

To use this module, we need to import the module in our application

Open terminal and type

$ npm install mongoose

Mongoose is a very popular ORM (Object Relations Mapper) for MongoDB in Node.js. Mongoose provides an easy, schema-based solution to model application data. It includes built-in type casting, validation, query building, business logic hooks.

In the under-mentioned diagram, we created a collection (database in other databases) name Books and inserted a document named “Rich Dad Poor Dad” and “How to Win Friends”.

You need to have a basic knowledge of MongoDB.

We inserted few records in our collection

                                     

Mongo-demo.js

Step by Step Guide

1 Import mongoose module
In order to access MongoDB database, we need to install Mongoose module.

2 Connect it to the database URL.
MongoDb is generally served on PORT 27017.

/books is our existing database created on MongoDB.

3 Create a schema from Mogoose module.

4 Create a Model which is a template specifying attributes of the collection.

5 Check the URL and if url is path ‘/books’
Get Books printed to console.

Running mongo-demo.js file

 Output