We are learning how to setup an Angular Application. How about learning the basics of Mongo DB just to setup a quick Backend service running in no time.

Also please note that this is just a quick setup to run Mongo on Node JS for Application services. Just a simple Crud Operation can be implemented over it.

So let us begin by knowing the basic requirements. We need
– Node Js installed on the PC
– We need Mongo Server installed on PC

After these two are installed, Just restart your PC.

By Default Mongo Database is stored in
C:\data\db

For this to happen properly you must manually have the folder created named "data" and within that create a folder "db"

mongod

The above command when typed in Command prompt and excecuted. It runs a Mongo Server.

Also the database can be place at custom locations in our PC. For example you want a server setup in your PC at location "e:\app\server\data\db" instead of in "C" Drive location then just create the folders properly, make sure the data and db folders ate the last folders created within. Use the command below to create and run server in location "e:\app\server\data\db"

mongod --dbpath E:\app\server\data\db

mongod is used to run the server, Now we need something to Access the Database. Now we use Node js to Access the database. So in a folder install the following packages. First in empty folder run from command prompt…


npm init

then install from command prompt using

npm install --save-dev mongoose
nom install --save-dev express
npm install --save-dev body-parser

The package.json file will be as below.

package.json

{
"name": "mongoosepractice",
"version": "1.0.0",
"description": "",
"main": "Book.model.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"mongoose": "^4.6.4"
}
}

Now we need to add a file for our DB structure, use the below file to create the Schema.

Movie.model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var MovieSchema = new Schema({
title: String,
VideoLink:String,
rate: String,
imagesa:[],
category:[]
});

module.exports = mongoose.model('Movie', MovieSchema);

The below code controls the Api URLs, each function is called by its name.

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Movie = require('./Movie.model');
var port = 9000;
var db = 'mongodb://localhost/example';

mongoose.connect(db);
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); // * => allow all origins
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,OPTIONS,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Accept'); // add remove headers according to your needs
next()
})
app.use(bodyParser.urlencoded({
extended:true
}))

app.get('/',function(req,res){
res.send('Happy to be here');
});

app.get('/movies',function(req,res){
console.log('Getting all books');
Movie.find({}).
exec(function(err,results){
if(err){
res.send('error occured');
} else{
console.log(results);
res.json(results);
}
})
});

app.post('/addMovie',function(req,res){
Movie.create(req.body, function(err,movie){
if(err){
res.send('error not fouond');
}else{
res.send(movie);
};
});
});

app.post('/deleteMovie',function(req,res){
Movie.findOneAndRemove({_id: <a href="http://req.body.id">req.body.id</a>}, req.body, function(err,movie){
if(err){
res.send('error not fouond');
}else{
res.send("removed");
};
});
});

app.put('/moviesEdit/:id',function(req,res){
Movie.findOneAndUpdate({
_id: <a href="http://req.params.id">req.params.id</a>
},{ $set:
{title:req.body.title, category:req.body.category, rate:req.body.rate}},
{upsert:true},
function(err,movie){
if(err){
res.send('error not fouond');
}else{
res.send("Updated");
}});
});

app.get('/movies/:id',function(req,res){
Movie.findOne({
_id: <a href="http://req.params.id">req.params.id</a>
}).
exec(function(err,results){
if(err){
res.send('error occured');
} else{
console.log(results);
res.json(results);
}
})
});

app.listen(port, function(){
console.log('app running on port ' + port);
});

To run the API service we open up command prompt and write

node app

the code runs and the api runs in localhost:9000.
We will discuss more on Mongo DB functionalities in more future post. This piece of code is for quick setup for API calls for our Angular Applications.

Advertisements