Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Discussion on schemas in mongoose with nodejs

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 501
    Comment on it

    Welcome to FindNerd. Today we are going to discuss schemas in mongoose with nodejs. There are other blogs available on FindNerd which are describing different features of nodejs so you can read out these blogs as well. Question is raised that what is schemas?
    Schema is nothing but a structure for the database table. You can set the different fields for your database table and set the different constraints for database. A table can contain different entities like name with string data-type so these structure or rules are called schema. We are going to take an example on schemas in mongoose. Please have a look.

    Step 1: Create application folder with any name. Here we are creating folder named schemas_demo

     

    Step 2 : Set the dependencies using package.json file for your application. Please check the file below.

    //package.json
    {
      "name": "application-name",
      "version": "0.0.1",
      "private": true,
      "scripts": {
        "start": "node app.js"
      },
      "dependencies": {
        "express": "3.4.0",
        "pug": "*",
        "mongoose": "~3.6.19"
      }
     }

    In above code we have defined all dependencies. Set the express,pug,mongoose versions and set the name,version for the application. To install the dependencies, go to application folder and run the below command.

    npm install

     

    Step 3: Create folder named public and paste the file bootstrap.min.css. You can download the bootstrap files from github or bootstrap website.

     

    Step 4: Crete a folder named train and create two files index.js and package.json. Kindly check the code below.

    //index.js
     var Train = function () {
    	this.data = {
    		number: null,
    		origin: null,
    		destination: null,
    		departs: null,
    		arrives: null,
    		actualDepart: null,
    		actualArrive: null
    	};
    
    	this.fill = function (info) {
    		for(var prop in this.data) {
    			if(this.data[prop] !== 'undefined') {
    				this.data[prop] = info[prop];
    			}
    		}
    	};
    
    	this.triggerDepart = function () {
    		this.data.actualDepart = Date.now();
    	};
    
    	this.triggerArrive = function () {
    		this.data.actualArrive = Date.now();
    	};
    
    	this.getInformation = function () {
    		return this.data;
    	};
    };
    
    module.exports = function (info) {
    	var instance = new Train();
    
    	instance.fill(info);
    
    	return instance;
    };  
    

     

    //package.json
    {
      "name": "train",
      "version": "0.0.0",
      "description": "A module for keeping track of a train",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Deepak Verma <deepakverma.3008@gmail.com>",
      "license": "BSD-2-Clause"
    }
    

    It is a custom module. We will use these functions later in our application.

     

    Step 5: Create db.js in root directory of your application and paste the below code.

    // db.js
    var mongoose = require('mongoose');
    
    mongoose.connect('<enter your connection string here>');
    
    module.exports = mongoose.connection;

    You need to paste the connection string from mlab in above code.

     

    Step 6:  Create app.js file and paste the below code.

    module.exports = function (trains) {
    	var express = require('express');
    	var routes = require('./routes')(trains);
    	var path = require('path');	
    	var app = express();
    
    	// all environments
    	app.set('port', process.env.PORT || 3000);
    	app.set('views', __dirname + '/views');
    	app.set('view engine', 'pug');
    	app.use(express.favicon());
    	app.use(express.logger('dev'));
    	app.use(express.bodyParser());
    	app.use(express.methodOverride());
    	app.use(function (req, res, next) {
    		res.set('X-Powered-By', 'Train Tracker');
    		next();
    	});
    	app.use(app.router);
    	app.use(express.static(path.join(__dirname, 'public')));
    
    	// development only
    	if ('development' == app.get('env')) {
    	  app.use(express.errorHandler());
    	}
    
    	app.get('/train/:number', routes.train);
    	app.put('/train/:number/arrived', routes.arrived);
    	app.get('/list', routes.list);
    
    	return app;
    }

    In above code we are using express and path frameworks to set the different options. We are using get,put functions as well.

     

    Step 7: Create folder data and then create file named index.js

    module.exports = {
    	"657": {
    		"number": 657,
    		"origin": "WUE",
    		"destination": "VGT",
    		"departs": "17:00",
    		"arrives": "19:00"
    	},
    
    	"233": {
    		"number": 233,
    		"origin": "YTR",
    		"destination": "RTE",
    		"departs": "19:00",
    		"arrives": "22:00"
    	}
    };

    This is testing data for train schedules. You can add more data as well.

     

    Step 8: Create folder named views and then create two files named list.pug and layout.pug. Kindly check the code below.

    // layout.pug
    doctype 5
    html
    	head
    		title= title
    		link(rel="stylesheet", href="bootstrap.min.css")
    	body
    		div.container
    			block content

     

    // list.pug
    extends layout
    
    block content
    	h1= title
    	ul
    		each train, index in trains
    			- train = train.getInformation()
    			li= train.number + ': ' + train.origin + '-' + train.destination

    We created layout.pug file and linked the bootstrap.min.css file and extended the layout inside list.pug. Above files are responsible to list the trains with their details.

     

    Step 9: Create schemas folder and then create train.js, paste the below code

    //train.js
    var mongoose = require('mongoose');
    
    module.exports = mongoose.model('Train', {
    	number: Number,
    	origin: String,
    	destination: String,
    	departs: String,
    	arrives: String,
    	actualDepart: Number,
    	actualArrive: Number
    });

     

     

    Step 10: Create server.js and paste the below code

    var http = require('http'),
    	trains = require('./data'),
    	db = require('./db'),
    	app = require('./app')trains);
    
    http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
    });

    In above code we have loaded modules http, data, app.js and db and have created the server for listening.

     

    Step 11 : Create folder named routes and then create a file index.js. Kindly check the code below.

    var TrainSchema = require('../schemas/train');
    
    module.exports = function (trains) {
    	var train = require('../train');
    
    	for(var number in trains) {
    		trains[number] = train(trains[number]);
    	}
    
    	var functions = {};
    
    	functions.train = function(req, res){
    		var number = req.param('number');
    
    		if (typeof trains[number] === 'undefined') {
    			res.status(404).json({status: 'error'});
    		} else {
    			res.json(trains[number].getInformation());
    		}
    	};
    
    	functions.arrived = function (req, res) {
    		var number = req.param('number');
    
    		if (typeof trains[number] === 'undefined') {
    			res.status(404).json({status: 'error'});
    		} else {
    			trains[number].triggerArrive();
    
    			var record = new TrainSchema(
    				trains[number].getInformation()
    			);
    
    			record.save(function(err) {
    				if (err) {
    					console.log(err);
    					res.status(500).json({status: 'failure'});
    				} else {
    					res.json({status: 'success'});
    				}
    			});
    
    			res.json({status: 'done'});
    		}
    	};
    
    	functions.list = function (req, res) {
    		res.render('list', {
    			title: 'All Trains', 
    			trains: trains});
    	};
    
    	return functions;
    };
    

    In above code we have loaded the mongoose schemas and we are getting record with train number and saving in the database using save method.

     

    Step 12:  Run the below command to start the application.

    node server.js

     

    You can get the train details by below URL
    http://localhost:3000/train/233/

    You need to use the PUT method to store the actual arrival. Kindly use postman to use the PUT method.
    http://localhost:3000/train/233/arrived

     

    Thank you for being with us!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: