Advertisement
Guest User

Untitled

a guest
Jun 28th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.46 KB | None | 0 0
  1. MVC
  2.  
  3. Using our Rats_Restaurant_app as reference to set up MVC and Mongo DB
  4.  
  5. 1. Create main directory and app.js
  6. 2. npm install express morgan fs path body-parse ejs
  7. 3. cd into main directory and npm init
  8. 4. Create models, views, controllers, public, directories
  9. 5. In views folder, create ejs files, link css, jquery, javascript
  10. 6. Declare all variables and set up app.js
  11.  
  12. ========== APP.js =============
  13.  
  14. 'use strict'
  15. const express = require('express')
  16. const app = express()
  17. const path = require('path')
  18. const bodyParser = require('body-parser')
  19. const logger = require('morgan')
  20. const PORT = process.env.PORT || 3000
  21.  
  22.  
  23. - Set variables to the controller files
  24. const homeController = require('./controllers/home_controller')
  25. const ratsController = require('./controllers/rats_controller')
  26. const restaurantsController = require('./controllers/restaurants_controller')
  27. const apiController = require('./controllers/api_controller')
  28.  
  29. - Set variables to the model js files
  30. const dbRats = require('./models/rats')
  31. const dbRestaurants = require('./models/restaurants')
  32.  
  33. - Uses Morgan logger to log
  34. app.use( logger('dev') );
  35.  
  36. - Applies express to the js files in Public folder
  37. app.use(express.static(path.join(__dirname, 'public')));
  38.  
  39. - Formats the json file in the return response
  40. app.use (bodyParser.json());
  41.  
  42. - Looks in the views folder for ejs files
  43. app.set('view engine', 'ejs');
  44.  
  45. - Sets a shortcut for the path to the views folder
  46. app.set('views', path.join(__dirname, 'views'));
  47.  
  48. - Directs user to the controllers folder
  49. app.use('/', homeController);
  50. app.use('/api', apiController);
  51. app.use('/rats', ratsController);
  52. app.use('/restaurants', restaurantsController);
  53.  
  54. - Sets the port to 3000
  55. app.listen(PORT, function(){
  56. console.log('Running on PORT ', PORT)
  57. });
  58.  
  59.  
  60. ====== CONTROLLERS/ HOME_CONTROLLER.js ========
  61.  
  62.  
  63. - Uses npm exress
  64. const express = require('express');
  65.  
  66. - Create variable for exporting
  67. const router = express.Router();
  68.  
  69. - Get request function which renders home_index.ejs
  70. router.get('/', function(req, res){
  71. res.render('home_index')
  72. })
  73.  
  74. - Exporting Data
  75. module.exports = router;
  76.  
  77.  
  78.  
  79. ======== CONTROLLERS/ RATS_CONTROLLER.js =========
  80.  
  81.  
  82. - same as home_controller except renders rat_index.ejs
  83.  
  84.  
  85. ======== CONTROLLERS/ API_CONTROLLER.js ===========
  86.  
  87. - Uses npm express
  88. const express = require('express');
  89.  
  90. - Set variable for exporting
  91. const router = express.Router();
  92.  
  93. - Sets variable to our Models folder
  94. const ratsData = require('../models/rats')
  95. const restaurantsData = require('../models/restaurants')
  96.  
  97. - Get request function that has a middleware function (ratsData.searchRats)
  98. - res.json will return us the json with a filter function (res.filteredRats)
  99. - res.filteredRats is from our MODEL/RATS.js
  100. router.get('/rats', ratsData.searchRats, function(req, res){
  101. res.json(res.filteredRats)
  102. })
  103.  
  104. - Same as above
  105. router.get('/restaurants', restaurantsData.searchRestaurants, function(req, res){
  106. console.log('back-end triggered');
  107. res.json(res.filteredRestaurants)
  108. });
  109.  
  110. - Exports this page
  111. module.exports = router;
  112.  
  113.  
  114. =========== MODELS/ RATS.js ===============
  115.  
  116. - Requires our rats.json file
  117. const ratsJSON = require('../rats.json')
  118.  
  119.  
  120. - npm install mongo in terminal. Open new window and run mongod and new window for mongo
  121. - Type mongoimport --db rats --collection ratsDB --drop --file rats.json --jsonArray
  122. - You can see by running Mongo, then show dbs, use rats, show collections
  123. const MongoClient = require('mongodb').MongoClient
  124.  
  125. - Uses default port 27017 and the name of the db name (rats) from above mongoimport
  126. const dbConnection = 'mongodb://localhost:27017/rats'
  127.  
  128. - Exporting this page
  129. module.exports = {
  130.  
  131.  
  132. - Creating a function called SearchRats which will serve a middleware function
  133. - Because the parameters (req,res,next)
  134. - Create an empty object (fileterObj)
  135. - If there is 'address' in our request query, then we will use
  136. this filterObj.incident address : req.query.address
  137. - Same for 'status'
  138.  
  139. searchRats: function(req, res, next){
  140. const filterObj = {};
  141. if ('address' in req.query){
  142. filterObj['incident_address']= new RegExp('^'+req.query.address,'i');
  143. }
  144. if ('status'in req.query){
  145. filterObj['status']= new RegExp('^'+req.query.status,'i')
  146. }
  147. console.log(filterObj);
  148.  
  149. - Connecting to db database
  150. MongoClient.connect(dbConnection, function(err,db){
  151. if (err)throw err;
  152.  
  153. - Passes our db collection name (ratsData) into Mongo
  154. - Finds our filterObj in ratsData
  155. - Puts it into an Array because we did json array in the mongo command above
  156. - data = res.filteredRats - will use a parameter in our CONTROLLER get function
  157. - Trigger next() since it is a middleware function
  158.  
  159. db.collection('ratsData')
  160. .find(filterObj)
  161. .toArray(function(err, data){
  162. if(err)throw err
  163. res.filteredRats = data
  164. next()
  165. })
  166. })
  167. }
  168. }
  169.  
  170. =========== PUBLIC/JS/ratsScript.js ==============
  171.  
  172. 'use strict'
  173.  
  174. - Declare variables for body tag
  175. - Declare variables for creating ul tags
  176. - Create a variable for our search button which will trigger an event
  177.  
  178. $(document).ready(function() {
  179. const $body = $('body');
  180. const $ul = $('<ul>');
  181. const $button = $('.searchForRats');
  182.  
  183. - On Click button, we will create an empty object
  184. - If the input tag (.address) does not equal to an empty string then
  185. - searchedValues.incident_address : value
  186. - same for (.status)
  187.  
  188.  
  189. $button.click(function(){
  190. const searchedValues = {};
  191. if($('.address').val()!== ''){
  192. searchedValues['incident_address'] = $('.address').val();
  193. console.log(searchedValues)
  194. }
  195.  
  196. if ($('.status').val()!== ''){
  197. searchedValues['status'] = $('.status').val();
  198. console.log(searchedValues)
  199. }
  200.  
  201. - Using ajax as a GET function to search json file based on our variable searchedValues
  202. - In this case searchedValues will contain 2 keys (incident_address) and (status)
  203. - Success function will fire
  204. - For each element in our object data we will create <li> tags for $status and $address
  205. - Then it append our data to the HTML body.
  206.  
  207. $.ajax ({
  208. url:'/api/rats',
  209. method: 'GET',
  210. dataType:'json',
  211. data: searchedValues,
  212. success: function(data){
  213. console.log(data)
  214. data.forEach(function(rats){
  215. let $status = $('<li>').text(rats.status)
  216. let $address = $('<li>').text(rats.incident_address)
  217. $ul.append($status);
  218. $ul.append($address);
  219. })
  220. $body.append($ul)
  221. }
  222. })
  223. })
  224. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement