MEAN, get some stuff out of MONGO DB, show JSON in restful style

Source: Internet
Author: User

I've been working on this lately.

The JavaScript style is ripe, I feel sure soon, but there is a feeling in my heart, Django and mean this structure, make big not.

Because this structure of MVC feels less rigorous than spring, is it my bias? The level is not enough? Not forced to do it?

DB Layer notation:

/** * Created by Sahara on 2016/7/5.*/varMongoose = require (' Mongoose '));varDburi = ' mongodb://localhost/loc8r ';varGracefulshutdownmongoose.connect (Dburi); Mongoose.connection.on (' Connected ',function() {Console.log (' Mongoose connected to ' +Dburi);}); Mongoose.connection.on (' Error ',function(Err) {Console.log (' Mongoose connection error: ' +err);}); Mongoose.connection.on (' Disconnected ',function() {Console.log (' Mongoose disconnected ');});varReadLine = require ("ReadLine");if(Process.platform = = = "Win32"){    varRL =Readline.createinterface ({input:process.stdin, output:process.stdout}); Rl.on ("SIGINT",function() {Process.emit ("SIGINT"); });} Gracefulshutdown=function(MSG, callback) {Mongoose.connection.close (function() {Console.log (' Mongoose disconnected through ' +msg);    Callback (); });}; Process.once (' SIGUSR2 ',function() {Gracefulshutdown (' Nodemon restart ',function() {Process.kill (Process.pid,' SIGUSR2 '); });}); Process.on (' SIGINT ',function() {Gracefulshutdown (' App termination ',function() {Process.exit (0); });}); Process.on (' SIGTERM ',function() {Gracefulshutdown (' Heroku app shutdown ',function() {Process.exit (0); });}); Require ('./locations ');

Database definition:

/** * Created by Sahara on 2016/7/5.*/varMongoose = require (' Mongoose '));varOpeningtimeschema =NewMongoose. Schema ({days: {type:string, Required:true}, Opening:string, closing:string, closed: {Type:boolean, Required:true}});varReviewschema =NewMongoose. Schema ({author:string, rating: {type:number, Required:true, min:0, Max:5}, Reviewtext:string, CreatedOn: {type:date,"Default": Date.now}});varLocationschema =NewMongoose. Schema ({name: {type:string, Required:true}, Address:string, Rating: {type:number,"Default": 0, min:0, max:5}, Facilities: [String], coords: {type: [number], index:' 2dsphere '}, Openingtimes: [Openingtimeschema], Reviews: [Reviewschema]}); Mongoose.model (' Location ', locationschema);

Routing layer notation:

varExpress = require (' Express ');varRouter =Express. Router ();varCtrllocations = require ('.. /controllers/locations ');varCtrlreviews = require ('.. /controllers/reviews ');//LocationsRouter.get ('/locations ', ctrllocations.locationslistbydistance); Router.post ('/locations ', ctrllocations.locationscreate); Router.get ('/locations/:locationid ', Ctrllocations.locationsreadone); Router.put ('/locations/:locationid ', ctrllocations.locationsupdateone); router.Delete('/locations/:locationid ', ctrllocations.locationsdeleteone);//ReviewsRouter.post ('/locations/:locationid/reviews ', ctrlreviews.reviewcreate); Router.get ('/locations/:locationid/reviews/:reviewid ', Ctrlreviews.reviewreadone); Router.put ('/locations/:locationid/reviews/:reviewid ', ctrlreviews.reviewupdateone); router.Delete('/locations/:locationid/reviews/:reviewid ', Ctrlreviews.reviewdeleteone); Module.exports= Router

Controller notation:

/** * Created by Sahara on 2016/7/6.*/varMongoose = require (' Mongoose '));varLoc = Mongoose.model (' Location ');varSendjsonresponse =function(res, status, content) {res.status (status); Res.json (content);}; Module.exports.locationsListByDistance=function(req, res) {Sendjsonresponse (res,$, {"status": "Success"});}; Module.exports.locationsCreate=function(req, res) {Sendjsonresponse (res,201, {"status": "Success"});}; Module.exports.locationsReadOne=function(req, res) {if(Req.params &&Req.params.locationid) {Loc. FindByID (Req.params.locationid). EXEC (function(err, location) {if(!Location ) {Sendjsonresponse (res,404, {                        "Message": "LocationID not Found"                    }); return; } Else if(Err) {Sendjsonresponse (res,404, err); return; } sendjsonresponse (res,200, location);    }); } Else{sendjsonresponse (res,404, {            "Message": "No LocationID in Request"        }); }};module.exports.locationsupdateone=function(req, res) {Sendjsonresponse (res,$, {"status": "Success"});}; Module.exports.locationsDeleteOne=function(req, res) {Sendjsonresponse (res,204, {"Status": "Success"});};

Modification of App.js:

varExpress = require (' Express ');varPath = require (' path ');varFavicon = require (' Serve-favicon '));varLogger = require (' Morgan ');varCookieparser = require (' Cookie-parser '));varBodyparser = require (' Body-parser ')); require ('./app_api/models/db ');varRoutes = require ('./app_server/routes/index '));varRoutesapi = require ('./app_api/routes/index '));varUsers = require ('./app_server/routes/users '));varApp =Express ();//View engine SetupApp.set (' Views ', Path.join (__dirname, ' app_server '), ' views ')); App.set (' View engine ', ' Jade ');//uncomment after placing your favicon in/public//App.use (Favicon (Path.join (__dirname, ' public ', ' Favicon.ico ' ));App.use (Logger (' dev ')) ; App.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ({extended:false}); App.use (Cookieparser ()); App.use (express.static (Path.join,' Public ')) ; App.use (‘/‘, routes); App.use ('/api ', Routesapi); App.use ('/users ', users);//catch 404 and forward to error handlerApp.use (function(req, res, next) {varErr =NewError (' Not Found '); Err.status= 404; Next (err);});//Error Handlers//Development Error Handler//Would print StackTraceif(App.get (' env ') = = = ' Development ') {App.use (function(Err, req, res, next) {Res.status (Err.status|| 500); Res.render (' Error ', {message:err.message, error:err}); });}//Production Error Handler//no stacktraces leaked to userApp.use (function(Err, req, res, next) {Res.status (Err.status|| 500); Res.render (' Error '{message:err.message, error: {}}); Module.exports= app;

MEAN, get some stuff out of MONGO DB, show JSON in restful style

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.