Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- MVC
- Using our Rats_Restaurant_app as reference to set up MVC and Mongo DB
- 1. Create main directory and app.js
- 2. npm install express morgan fs path body-parse ejs
- 3. cd into main directory and npm init
- 4. Create models, views, controllers, public, directories
- 5. In views folder, create ejs files, link css, jquery, javascript
- 6. Declare all variables and set up app.js
- ========== APP.js =============
- 'use strict'
- const express = require('express')
- const app = express()
- const path = require('path')
- const bodyParser = require('body-parser')
- const logger = require('morgan')
- const PORT = process.env.PORT || 3000
- - Set variables to the controller files
- const homeController = require('./controllers/home_controller')
- const ratsController = require('./controllers/rats_controller')
- const restaurantsController = require('./controllers/restaurants_controller')
- const apiController = require('./controllers/api_controller')
- - Set variables to the model js files
- const dbRats = require('./models/rats')
- const dbRestaurants = require('./models/restaurants')
- - Uses Morgan logger to log
- app.use( logger('dev') );
- - Applies express to the js files in Public folder
- app.use(express.static(path.join(__dirname, 'public')));
- - Formats the json file in the return response
- app.use (bodyParser.json());
- - Looks in the views folder for ejs files
- app.set('view engine', 'ejs');
- - Sets a shortcut for the path to the views folder
- app.set('views', path.join(__dirname, 'views'));
- - Directs user to the controllers folder
- app.use('/', homeController);
- app.use('/api', apiController);
- app.use('/rats', ratsController);
- app.use('/restaurants', restaurantsController);
- - Sets the port to 3000
- app.listen(PORT, function(){
- console.log('Running on PORT ', PORT)
- });
- ====== CONTROLLERS/ HOME_CONTROLLER.js ========
- - Uses npm exress
- const express = require('express');
- - Create variable for exporting
- const router = express.Router();
- - Get request function which renders home_index.ejs
- router.get('/', function(req, res){
- res.render('home_index')
- })
- - Exporting Data
- module.exports = router;
- ======== CONTROLLERS/ RATS_CONTROLLER.js =========
- - same as home_controller except renders rat_index.ejs
- ======== CONTROLLERS/ API_CONTROLLER.js ===========
- - Uses npm express
- const express = require('express');
- - Set variable for exporting
- const router = express.Router();
- - Sets variable to our Models folder
- const ratsData = require('../models/rats')
- const restaurantsData = require('../models/restaurants')
- - Get request function that has a middleware function (ratsData.searchRats)
- - res.json will return us the json with a filter function (res.filteredRats)
- - res.filteredRats is from our MODEL/RATS.js
- router.get('/rats', ratsData.searchRats, function(req, res){
- res.json(res.filteredRats)
- })
- - Same as above
- router.get('/restaurants', restaurantsData.searchRestaurants, function(req, res){
- console.log('back-end triggered');
- res.json(res.filteredRestaurants)
- });
- - Exports this page
- module.exports = router;
- =========== MODELS/ RATS.js ===============
- - Requires our rats.json file
- const ratsJSON = require('../rats.json')
- - npm install mongo in terminal. Open new window and run mongod and new window for mongo
- - Type mongoimport --db rats --collection ratsDB --drop --file rats.json --jsonArray
- - You can see by running Mongo, then show dbs, use rats, show collections
- const MongoClient = require('mongodb').MongoClient
- - Uses default port 27017 and the name of the db name (rats) from above mongoimport
- const dbConnection = 'mongodb://localhost:27017/rats'
- - Exporting this page
- module.exports = {
- - Creating a function called SearchRats which will serve a middleware function
- - Because the parameters (req,res,next)
- - Create an empty object (fileterObj)
- - If there is 'address' in our request query, then we will use
- this filterObj.incident address : req.query.address
- - Same for 'status'
- searchRats: function(req, res, next){
- const filterObj = {};
- if ('address' in req.query){
- filterObj['incident_address']= new RegExp('^'+req.query.address,'i');
- }
- if ('status'in req.query){
- filterObj['status']= new RegExp('^'+req.query.status,'i')
- }
- console.log(filterObj);
- - Connecting to db database
- MongoClient.connect(dbConnection, function(err,db){
- if (err)throw err;
- - Passes our db collection name (ratsData) into Mongo
- - Finds our filterObj in ratsData
- - Puts it into an Array because we did json array in the mongo command above
- - data = res.filteredRats - will use a parameter in our CONTROLLER get function
- - Trigger next() since it is a middleware function
- db.collection('ratsData')
- .find(filterObj)
- .toArray(function(err, data){
- if(err)throw err
- res.filteredRats = data
- next()
- })
- })
- }
- }
- =========== PUBLIC/JS/ratsScript.js ==============
- 'use strict'
- - Declare variables for body tag
- - Declare variables for creating ul tags
- - Create a variable for our search button which will trigger an event
- $(document).ready(function() {
- const $body = $('body');
- const $ul = $('<ul>');
- const $button = $('.searchForRats');
- - On Click button, we will create an empty object
- - If the input tag (.address) does not equal to an empty string then
- - searchedValues.incident_address : value
- - same for (.status)
- $button.click(function(){
- const searchedValues = {};
- if($('.address').val()!== ''){
- searchedValues['incident_address'] = $('.address').val();
- console.log(searchedValues)
- }
- if ($('.status').val()!== ''){
- searchedValues['status'] = $('.status').val();
- console.log(searchedValues)
- }
- - Using ajax as a GET function to search json file based on our variable searchedValues
- - In this case searchedValues will contain 2 keys (incident_address) and (status)
- - Success function will fire
- - For each element in our object data we will create <li> tags for $status and $address
- - Then it append our data to the HTML body.
- $.ajax ({
- url:'/api/rats',
- method: 'GET',
- dataType:'json',
- data: searchedValues,
- success: function(data){
- console.log(data)
- data.forEach(function(rats){
- let $status = $('<li>').text(rats.status)
- let $address = $('<li>').text(rats.incident_address)
- $ul.append($status);
- $ul.append($address);
- })
- $body.append($ul)
- }
- })
- })
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement