The previous article describes the use of the template engine Pug.js, which is mainly written in the background logic.
Backstage most of the functions have, but in the state of being logged in, the foreground and the background of the logical processing is not very perfect.
First a few pictures, like the old version of the book, changed the UI, because there is no simple book so much content, so there is no need to completely make the same.
1. Project structure
app.js is the entrance to the entire project.
The logic of the model folder to put the connected database
The public folder is full of static resources.
The Router folder is the routing file for each module, androute.js is the total entry
upload is the uploaded image file.
views are all templates,Layout.pug is the outermost framework template, and Components and pages are templates for public and individual pages.
2.app.js
App.js Code:
App.js is the entire project entrance, there is no problem here, the template engine configuration and static file item configuration in the document are described. Note that the static file settings here, it is best to use Path.join, because I follow the above settings template engine writing to write, always error, can not find the corresponding file.
3.router
In this folder is all the relevant configuration of the route
Route.js
Articlelist.js
Router part by my business-related, divided into a login, article, management three parts. Each part will write their relevant request logic in a JS file, and then exposed the router interface at the bottom, and finally in the Route.js Unified distribution processing.
In Router.js, all the routes are hung on the App object, and then exposed to the app for use in the portal file app.js.
In addition, the session is also used to save the login status, you can use req.session.xxx to get or create a new and save a property.
The only problem here is that after the maxage is set up, no matter if there is no operation in the middle of the page, as long as the time is up, the cookie will be erased, not as long as the page is active, the cookie will not expire. I don't know if I have a problem with my settings.
Login.js
Login logic to do is relatively simple, just to get the value from the foreground, and then compare with the values in the database, and do not do validation and encryption processing, in the actual project should be added.
The POST request is also used, and the body-parser middleware must be introduced separately for the post request to get the value of the post passed in.
4.model
The model section is primarily responsible for connecting to the database, getting and returning values.
Connect.js
The Connect.js file is primarily responsible for connecting to the database and exposing the DB object so that it can be referenced directly in other areas of need without having to connect again.
Article_list.js file code more, directly copied over.
varMongoose = require (' Mongoose '));//Define schemavarArticleschema =NewMongoose. Schema ({author:string, createtime:string, updatetime:string, type:string, label:string, title:string, DESCRI Ption:string, Content:string, text:string, Delta:object, Pv:number, Likes:number, image:string})//operations before depositing to the databaseArticleschema.pre (' Save ',function(next) {varDate =NewDate (); if( This. IsNew) { This. UpdateTime = This. Createtime = date.getfullyear () + '-' + (Date.getmonth () + 1) + '-' +date.getdate (); } Else { This. UpdateTime = date.getfullyear () + '-' + (Date.getmonth () + 1) + '-' +date.getdate (); } Next ()});//defining the model, associating related tablesvarArticlemodel = Mongoose.model (' article_list '), Articleschema);functionfindarticle (option, callback) {articlemodel.find (option,function(err, result) {if(Err) console.log (err); //Render Template vardata ={Articlelists:result}; Callback (Data)})}//render a list of articlesvarRenderarticlelist =function(ArticleType, callback) {Switch(articletype) { Case' All ': Findarticle ({}, callback) Break; Case' Novel ': Findarticle ({type: ' novel ')}, Callback) Break; Case' It ': findarticle ({type: ' programming ')}, Callback) Break; default: Res.send (' not yet! ')) }};//Render article detailsvarRenderarticle =function(ArticleID, callback) {varArticleID =mongoose.mongo.ObjectId (ArticleID) articlemodel.find ({_id:articleid},function(err, result) {if(Err) console.log (err); Callback (result[0]) })}//like number increasevarAddlike =function(req, res) {}//article manage list paging get datavarRendermanage =function(OPT, callback) {varCurrentSize = (opt.currentpage-1) *opt.pagesize; Articlemodel.find ({},function(err, result) {vardata ={Articlelists:result}; Callback (Result)}). Skip (CurrentSize). Limit (opt.pagesize)}//article manage list get totalvarGetLength =function(callback) {Articlemodel.find ({},function(err, result) {callback (Result.length)})}//article edit SavevarSavearticle =function(Article_opt, callback) {varNewarticle =NewArticlemodel (article_opt); if(article_opt.params_id) {var_id =article_opt.params_id articlemodel.findoneandupdate ({_id: _id}, Article_opt,function(err, result) {callback (RESULT._ID)})} Else{Newarticle.save (function(err, result) {callback (RESULT._ID)})}}//article DeletevarDeletearticle =function(ArticleID, callback) {Articlemodel.remove ({_id:articleid},function(err, result) {Console.log (Result) callback ()})}varModelhome ={renderarticlelist:renderarticlelist, renderarticle:renderarticle, Rendermanage:rendermanage, Getlength:getl Ength, savearticle:savearticle, Deletearticle:deletearticle};module.exports= Modelhome;
All the logic involved in the Article_lists table will be written in the article_list.js, but this should be optimized, because this should only be done with the model part, not the logical operation part.
When using the Mongoose Library to connect to MongoDB, it is important to note that when defining the model, associated tables, var articlemodel = Mongoose.model (' Article_list ', Articleschema); The article_list here corresponds to the table article_lists in your database, and the table in the database is more than one s.
In the editing of the article, in addition to the new article, you can also directly modify the existing article, so this involves data interpolation and update, if the use of native MongoDB method, can be very simple through the Save () method to achieve, but in mongoose but not, The Save () method in Mongoose is basically the same as the native Insert ().
So it takes two steps to use Mongoose, update the value using Findoneandupdate (), and create a new using the Save () method.
Conclusion:
In this version, there are some features did not do, such as the likes of like, but the big features have, but the rest I do not intend to write again, and then it must be refactoring.
The reason for this is that I can find many places to optimize, and most importantly, Express is a lightweight framework, he is flexible, but a lot of things need to use third-party plugins or libraries, which brings a lot of trouble.
Third-party library mixed, in the original choice above, you need to spend a lot of effort, after the election, you have to learn from each other, to step into the pit, which is very troublesome, so it is not recommended that you directly in the company's important projects directly use express this framework.
Of course, if it's just some simple pages, such as the active page or some pages that don't design too many front-end logic interactions, you can still use express, because it's really simple, you don't need to get the ES6 to figure it out first, and you don't need to get it all figured out.
Simply take a look at the Express website and quickly get started with something that has a front-back interaction.
Blog system based on Express+mongodb+pug--backstage article