Tuesday, May 19, 2015

NodeJs with MongoDB

In my last post I showed how to write a NodeJS application using EJS view engine. In this post I will explain how to integrate NodeJS application with MongoDB.
First we need to install Mongoose module.
It is better if we save the mongodb connection in a environment specific file. Create a new folder called env in config  folder and add development.js file into that. The content of that file should be like below.
Now add a configuration file into config folder like below. Depending on the Node environment, the config file will load appropriate node environment file.
Add a file called mongoose.js into config folder, which contains mongodb related configurations.
Now we have to initialize mongoose configuration in server.js file. Notice, I have added environmental configurations in server.js file.
Then create student schema in app/model folder. In here first you will define your StudentSchema using Schema constructor. Then you will add Student model using StudentSchema instance.
First you must register the Student model in mongoose.js file like below.
Make sure, mongose configuration file is loaded before any other configuration file is loaded.
Change controller functionality accordingly.
Browse http://localhost:3000/ location. You will see results like below.

No comments:

Post a Comment