Skip to main content

Creating models with mongoose

Greetings!

This is the 2nd part of our Node employee management system. In this part, we are going to create our model.

MongoDB

MongoDB is an open source NoSQL database that stores data as documents in JSON like structure. A "collection" of "documents", in a MongoDB database, is analogous to a "table" of "rows" in a relational database.

This combination is extremely popular because it helps to use same structure in entire application. (thus creating stacks like MEAN)

Mongoose

Mongoose is an Object Document Mapper(ODM) for Node. (like Hibernate for Java). It allows us to access MongoDB commands simply and easily.
https://www.npmjs.com/package/mongoose

Initialize database

* You need to have installed Mongo in your computer.
go to the terminal and do this,
$ mongo
> use nodeems;
> db.employees.insert({
   firstName: 'Manjula',
   lastName: 'Jayawardana',
   email: 'manjula121@gmail.com',
   password: 'manju'
});
> db.employees.find().pretty();

Install mongoose

This will add mongoose support to our project
$ npm install mongoose --save

Configure database

$ mkdir server/configs
$ touch server/configs/database.js

* update app.js to require database configuration
require("./server/configs/database");

Create mongoose schema

$ touch server/models/employee.js

Then mongoose will provide multiple methods to access data.
save(), find(), findOne(), findById(), findByIdAndRemove() and man more.

See you in next tutorial.




Comments