Mar 5, 2014

How to make a project with Node.js & MongoDB (CRUD) - Part 1



In this tutorial we will create a simple CRUD application (Create, Read, Update & Delete) with Node.js and MongoDB. We will use the Express framework and support of libraries Mongoose to handle MongoDB databases.




We need to have installed:

          - Node.js      (If you don't have it click here)
          - Express      (If you don't have it click here)
          - MongoDB (If you don't have it click here)

Now, we will create our project:



Create the project

1 - Open your terminal and headed to the directory where we want to create our project

2 - Write in the terminal:    $ express crudApp  

3 - Headed to the project folder and opened the file "package.json" and insert a new line in dependecies:


"dependencies": {
    "express": "3.4.8",
    "jade": "*",
    "mongoose": "*"
  }

this is the module that will allow us to chat communications

4 - choose de folder of the proyect in the terminal:    $  cd crudApp  

5 - install dependencies, write in the terminal:   $ npm install  



Create the DataBase

1 - Headed to the project folder and create a new folder called "Data".

2 -  Open your terminal and create de new DataBase, write: 
   $ mongod --dbpath  folder_data_url*     *change folder_data_url for your folder data url
 Warning: You can't close this terminal window.



Create the server

Open the file "app.js" and write:

1 - Below "var app = express();" write:

// ... code

var app = express();

// require the library mongoose
mongoose = require('mongoose');

// Connect with our database
mongoose.connect('mongodb://localhost/db_crudApp');

// Create the model of the database
var Schema = mongoose.Schema
var info = new Schema({
name: String,
email: String
});

// create de object of the model
var info = mongoose.model('info',info);

//... code

2 - Create the routes, add this code below "app.get('/users', user.list);":


// ... code

app.get('/', routes.index);
app.get('/users', user.list);

app.get('/contacts',function(req, res){
info.find({},function(err,data){
  res.render('contacts', { 
   title: 'Contacts',
  data: data
  });
});

});

app.post('/contacts',function(req, res){
newinfo = new info({ name: req.body.name, email: req.body.email});
newinfo.save(function(err){
if (err) {throw error;}
else {res.redirect('/contacts');}
});

});

// ... code



Create the view

Create a new jade file "views/contacts.jade" and write this:



becareful with the tabulated, jade is very sensitive with them


Run de App

Write in the terminal:   $ node app  and open your browser in localhost:3000/contacts


We can see de form to add a new contact and all the contacts.



Next Part

In the Part 2 we create de options of update and delete in the database




I hope you liked it, and if you have any questions feel free to write me:





  

No comments:

Post a Comment