Building a back-end MVC file structure under nodejs+express

Source: Internet
Author: User

There are basically two ways to structure MVC, one to classify folders by hierarchy, and the other to classify folders by business. About this demo-related business is simple, so the first way, of course, the actual very hate complex projects can be used in two ways to combine the way!

Not much to say the fee, and then our concrete structure, directly:

GitHub Address: Https://github.com/FicoHu/nodeserver

NODESV: root directory, as a folder for the entire Web project.

App: As a folder for the entire backend service, the point we're talking about is the structure under this folder.

Public as a folder on the front end of the entire project, followed by the chapters.

4 folders under App:

    • Controllers, representing the control layer
    • Libs, some common modules of the package, such as log operation module, file operation module, etc.
    • Model, representing the data layer
    • Routes, which represents the route
    • Views, which represents the view.

Some points to note:

For the name of the file, it is named by the object name + server + hierarchy , for example: Doc.server.controller.js, which represents the control layer file of the document module on the server side.

Focus on the contents of the controller, model, and route layer:

Doc.server.controller.js, the data operation in this module is encapsulated into a method, and then exposed externally, for example, inside this document module, adding methods such as creating, viewing lists, etc.

varMongoose = require ("Mongoose");varDocmodel = require (".. /models/doc.server.model "); Module.exports={create:function(req, res, next) {//var docentity = new Docmodel (req.body);        varDocentity =NewDocmodel ({title:' AAA ', type:' DD ', ext:'. jpg ', Size:1024, Content:' DSF ', Created:Date.now (), creater:' DSFADF '        });        Console.log (docentity); Docmodel.create (docentity,function(err) {if(ERR)returnNext (ERR); returnRes.json (docentity);    }); }, GetList:function(req, res, next) {varpagesize = parseint (req.query.pagesize, 10) | | 10; varPagestart = parseint (Req.query.pagestart, 10) | | 1; Console.log (pagesize+ "  " +Pagestart); Docmodel.find (). Skip ((Pagestart-1) +pagestart). Limit (pagesize). EXEC (function(err, results) {if(ERR)returnNext (ERR); if(!results)returnNextNewError (' Doc not found ')); returnRes.json (results); //return Res.json ({id:1,name: "dddd"});            }); }, GetById:function(req, res, next) {//if (!did) return next (New Error (' not Found '));Console.log (Req.params.did); Docmodel.findone ({_id:req.params.did}). EXEC (function(err, results) {if(ERR)returnNext (ERR); if(!results)returnNextNewError (' Doc not found ')); returnRes.json (results);    }); }};
View Code

Doc.server.model.js, as the data file for this module, defines the relevant fields for this module's contents.

varMongoose = require ("Mongoose");varDocschema =NewMongoose. Schema ({title:string, pid: {type:mongoose. Schema.Types.ObjectId, Index:true}, UID: {type:mongoose. Schema.Types.ObjectId, Index:true}, type: {type:number,//1 Identifying the document, 2 identifying the picture, 3 identifying the video, 4 identifying the otherIndextrue,        default: 0}, ext:string, size: {type:number,//file size, folder is 0        default: 0}, Content:buffer, docurl:string, status: {Type:number,//0 Identification as normal, 1 identity sharing        default: 0}, Isflag: {type:number,//0 identified as normal, 1 identity removed        default: 0}, created: {type:date,default: Date.now}, creater: {name:string, uid:mongoose. Schema.Types.ObjectId}, updated: {type:date,default: Date.now}, Updater: {name:string, uid:mongoose. SCHEMA.TYPES.OBJECTID}});varDocmodel = Db.model ("Docs", Docschema); Module.exports= Docmodel;
View Code

Doc.server.route.js, as the routing file for this module.

var express = require (' Express '); var docrouter = Express. Router (); var  Doccontroller=require ('.. /controllers/doc.server.controller ');d ocrouter.get ('/getlist ', doccontroller.getlist); Docrouter.get ('/create ', doccontroller.create);d ocrouter.get ('/getbyid/:d id '= docrouter;
View Code

These files already know the specific role of how to take these codes in a running order?

When the Web service starts, App.js is already loaded, and you need to define the route in the Appjs.
var Docroute = require ('./app/routes/doc.server.route.js ');
App.use ('/doc ', docroute);

1, the user initiated the request, http://www.xxxxx.club/doc/getList

2, node server, found that the app has set the doc routing

3, then node server, parse Docroute, navigate to./app/routes/doc.server.route.js inside to detail.

4, according to the detailed route, then specify the controller inside to the specific operation, for example: Docrouter.get ('/getlist ', doccontroller.getlist);

5, enter the controller, perform getlist operation.

6, if the getlist operation involves the model layer, then call the model layer related data structure.

6. The controller then returns the data to the user.

This is the whole MVC to the request process!

Building a back-end MVC file structure under nodejs+express

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.