Hello Worlds to NodeJS, RestFul, MongoDB

Posted on Actualizado enn

Here is a quick guide showing how to build a RESTful API using Node.js, Express, and MongoDB.

Installing Ubuntu desktop https://www.ubuntu.com/download/desktop 16.04.1 LTS

Installing jdk

sudo apt-get install openjdk-8-jdk
apt-cache search jdk
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk
export PATH=$PATH:/usr/lib/jvm/java-8-openjdk/bin
Installing Netbeans

Download the netbeans-8.2-linux.sh

I copied it to home/neatbeans folder and then
chmod +x <installer-file-name>. Type ./<installer-file-name>
$sudo chmod +x netbeans-*
$sudo ./netbeans-*
You can create and html5, nodejs application
sudo install nodejs npm
sudo npm install express-generator -g

*also I had to go to /usr/lib/jvm ls to pick up java-1.8.0-openjdk-amd64

and then edit the file /usr/local/netbeans-8.2/etc/

sudo gedit netbeans.conf

netbeans_jdkhome=”/usr/lib/jvm/java-1.8.0-openjdk-amd64″

Installing Node.js

  1. Go to http://nodejs.org, and click the Install button.
  2. Run the installer that you just downloaded. When the installer completes, a message indicates that Node was installed at /usr/local/bin/node and npm was installed at /usr/local/bin/npm.
  3. Or easier
    sudo apt-get install -y nodejs

Done, NodeJS is installed, let’s do a HelloWorld to test it!

  1. Create a folder named winecellar anywhere on your file system.
  2. In the wincellar folder, create a file named server.js.
  3. Code server.js as follows:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000');

We are now ready to start the server and test the application:

  1. To start the server, open a shell, cd to your nodecellar directory, and start your server as follows:

    node server.js

  2. To test the application, open a browser and access http://localhost:3000.

node server.js (windows) / nodejs server.js (linux)

Installing Express

Express is a lightweight node.js web application framework. It provides the basic HTTP infrastructure that makes it easy to create REST APIs.

To install Express in the nodecellar application:

  1. In the nodecellar folder, create a file named package.json defined as follows:
{
"name": "wine-cellar",
"description": "Wine Cellar Application",
"version": "1.0.0",
"private": true,
"dependencies": {
"express": "~4.14.0",
}
}

2.Open a shell, cd to the nodecellar directory, and execute the following command to install the express module.

npm install

or in netbeans right click over the project and npm install

A node_modules folder is created in the nodecellar folder, and the Express module is installed in a subfolder of node_modules.

Lets start trying our REST API with the following

  1. Open server.js and replace its content as follows:
var express = require('express');
var app = express();
app.get('/wines', function(req, res) {
res.send([{name:'wine1'}, {name:'wine2'}]);
});
app.get('/wines/:id', function(req, res) {
res.send({id:req.params.id, name: "The Name", description: "description"});
});
app.listen(3000);
console.log('Listening on p]rt 3000...');
  1. Stop (CTRL+C) and restart the server:

    node server

  2. To test the API, open a browser and access the following URLs:
    Get all the wines in the database: http://localhost:3000/wines
    Get wine with a specific id (for example: 1): http://localhost:3000/wines/1

So far, we have tested the server and the Get methods from a webserver.

Now, lets move the code to a related file, then we are going to declare dependency in server.js

  1. In the nodecellar folder, create a subfolder called routes.
  2. In the routes folder create a file named wines.js and defined as follows:
exports.findAll = function(req, res) {
res.send([{name:'wine1'}, {name:'wine2'}, {name:'wine3'}]);
};

exports.findById = function(req, res) {
res.send({id:req.params.id, name: "The Name", description: "description"});
};

3. Modify the server as follows

var express = require('express'),
wines = require('./routes/wines');

var app = express();

app.get('/wines', wines.findAll);
app.get('/wines/:id', wines.findById);

app.listen(3000);
console.log('Listening on port 3000...');

4.Restart and test.

Now MongoDB

Installing mongoDB

In windows https://www.mongodb.com/download-center I followed the wizard and then https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/

1.C:\>mkdir c:\data\log and C:\>mkdir c:\data\data

2. Create a file at C:\Program Files\MongoDB\Server\3.4\mongod.cfg that specifies both systemLog.path and storage.dbPath:

systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db

3.C:\>”C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe” –config “C:\Program Files\MongoDB\Server\3.4\mongod.cfg” –install

C:\>net start MongoDB
El servicio de MongoDB está iniciándose.

C:\>net stop MongoDB

at the end I run

4.PS C:\Program Files\MongoDB\Server\3.4\bin> .\mongod.exe

4 easy steps to install mongodb over ubuntu 16 

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
sudo apt-get update
sudo apt-get install -y mongodb-org
 ready.
$sudo service mongod start

$mongo

Installing the MongoDB Driver for Node.js

There are different solutions offering different levels of abstraction to access MongoDB from Node.js (For example, Mongoose and Mongolia). A comparaison of these solutions is beyond the scope of this article. In this, guide we use the native Node.js driver.

To install the the native Node.js driver, open a terminal window, cd to your nodecellar folder, and execute the following command:

npm install mongodb
Implementing the REST API

The full REST API for the nodecellar application consists of the following methods:

Method URL Action
GET /wines Retrieve all wines
GET /wines/5069b47aa892630aae000001 Retrieve the wine with the specified _id
POST /wines Add a new wine
PUT /wines/5069b47aa892630aae000001 Update wine with the specified _id
DELETE /wines/5069b47aa892630aae000001 Delete the wine with the specified _id

Installilng bodyParser:

$ npm install body-parser

 or

"dependencies": {
"express": "~4.14.0",
"body-parser": "~1.15.2"
}

and npm install

To implement all the routes required by the API, modify server.js as follows:

var express = require('express'),
    wine = require('./routes/wines');

var express = require('express');
    wine = require('./routes/wines');
//to get put (update) and post (insert)
var bodyParser = require('body-parser');
//var mongoose = require('mongoose');

var app = express();
//to get put (update) and post (insert)
app.use(bodyParser.json());

//app.use(bodyParser.urlencoded({extended: false}));

var app = express();

app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);

app.listen(3000);
console.log('Listening on port 3000...');

And the wines

var Wine = require('../models/wine');

var mongo = require('mongodb');
//mongo.BSONPure = require('bson').BSONPure;

var databaseName = 'winedb',
collectionName = 'wines';

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;
    //BSON = require('mongodb').BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db(databaseName, server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'winedb' database");
        db.collection(collectionName, {strict:true}, function(err, collection) {
            if (err) {
                console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});
console.log("...");

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving wine: ' + id);
    //collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
    //var o_id = new BSON.ObjectID(id);

    db.collection('wines', function(err, collection) {
        //collection.find({"country":"Spain"}).toArray(function(err, items) {
        //collection.find({'country':id}).toArray(function(err, items) {
        collection.find({'_id':new require('mongodb').ObjectID(req.params.id)}).toArray(function(err, items) {

        res.send(items);
        });
    });
};
/*
exports.findAll = function(req, res) {
    Wine.find(function(err,wines){
        if(err){
            console.log(err.message);
            rest.send(500,err.message);
        }
        console.log('all wine');
        rest.status(200).jsonp(wines);
    })
}*/

exports.findAll = function(req, res) {
    db.collection('wines', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addWine = function(req, res) {
    var wine = req.body;

    console.log('Adding wine0: ' + wine);
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {

        //collection.insert({
        //'name':'LAN RIOJA CRIANZA',
        //'year':'2006',
        //'grapes':'Tempranillo',
        //'country':'Spain',
        //'region':'Rioja',
        //'description':'A resurgence of interest in boutique vineyards...',
        //'picture':'lan_rioja.jpg'},{safe:true}, function(err, result) {

        if (err) {
     res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
};

exports.updateWine = function(req, res) {
    var id = req.params.id;
    var wine = req.body;
    console.log('Updating wineid: ' + id + ' wine:'+wine);
    console.log(JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
          collection.update({'_id':new require('mongodb').ObjectID(req.params.id)}, wine, {safe:true}, function(err, result) {
          //collection.update({'_id':new require('mongodb').ObjectID(req.params.id)}, {'yearid':'1000'}, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating wine: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(wine);
            }
        });
    });
};

exports.deleteWine = function(req, res) {
    var id = req.params.id;
    console.log('Deleting wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.remove({'_id':new require('mongodb').ObjectID(req.params.id)}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
};

/*
exports.findAll = function(req, res) {
    console.log('All Wines Request');
    res.send([{name:'wine1'}, {name:'wine2'}, {name:'wine3'}]);
};

exports.findById = function(req, res) {
    console.log('id='+req.params.id);
    res.send({id:req.params.id, name: "The Name", description: "description"});
};*/

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
/*
var populateDB = function() {
    var wines = [
    {
        name: "CHATEAU DE SAINT COSME",
        year: "2009",
        grapes: "Grenache / Syrah",
        country: "France",
        region: "Southern Rhone",
        description: "The aromas of fruit and spice...",
        picture: "saint_cosme.jpg"
    },
    {
        name: "LAN RIOJA CRIANZA",
        year: "2006",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "A resurgence of interest in boutique vineyards...",
        picture: "lan_rioja.jpg"
    }];
    db.collection('wines', function(err, collection) {
        collection.insert(wines, {safe:true}, function(err, result) {});
    });
};
*/

—-
And then, time to test.
I liked it Postman addon for chrome, as you know you can test get (all or byid) from the browser for the others you can use postman or restconsole another google extension http://restconsole.com/

Insert / post
captura

update / put
captura2

Delete is almost the same and get is in the browser too
………..

Vbox change size of hd over Ubuntu

C:\Program Files\Oracle\VirtualBox>vboxmanage.exe modifyhd “C:\Users\Hugo de la Mora\VirtualBox VMs\ASN\ASN.vdi” –resize 12000
0%…10%…20%…30%…40%…50%…60%…70%…80%…90%…100%

Then using gparted moving partitions can assign the unllocated partion
https://www.youtube.com/watch?v=cDgUwWkvuIY (great tutorial for resizing, playing with partitions)

1.-Move the extended at the end (linux-swap), turn off, resize/move, extend it to the end.
2.-linux-swap, resize/move, and move it to the end, unallocated comes second.
3.-Go to extended particion (blue), and make it little, let free space precding big.
4.-The click on the ext4, the partition we want to extend, we can do it on the graphical screen and apply all operations.

You can verify with disk utility in Ubuntu
****

Following this tutorial

http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s