[Node.js]express+mongoose+mongodb's development notes

Source: Internet
Author: User
Tags findone

Time flies fast, June and July busy, dejected is also a lot of things, Hangzhou, Dalian to fly back and forth, is also hehe.

I hope to immerse myself in the next stage and learn what I want to learn. Take a look at the lessons that have been written for several days in the last few weeks. Because of the reason for the class, so in a short time to understand the next EXPRESS+MONGODB combination, to the app has a simple server, also opened the background Web services. Briefly summarize the pits encountered during the development process.

First, about Express
Understand node. JS has more than half a year, the first time with node. JS Framework to write server, understand is not very deep, a simple look at the document after you can get started, the development of low difficulty.
1. Running
After Express Init thought it was the node App.js command to run the project, the result was not. App.js is the project entry file is good, but itself is a module modules, app.js code inside and no listenserver operation, Express Scaffolding command to start the project to bin/www file, need to start the application via NPM start.
The application via NPM start does not seem to be able to reboot [?] in real time, so you can transfer the WWW file to [New]start.js and Run node start.js, which can be monitored & restarted via supervisor or Nodemon.

2. Middleware
Express is middleware-based. The App.use ('/admin ', admin) handles all localhost/admin requests by introducing a middleware execution handler, for example, when processing a GET request that executes the function sequentially in app.js based on the routing condition. The specific second-level routing process is given to the route/admin.js. In this lesson, I only define a middleware cookie-checker for login identification. In Java or PHP can be detected by the filter or the entrance module to detect the cookie, judge login, express inside just simplified, directly define a cookie-checker middleware, placed in the App.use ('/api ', API) and App.use ('/admin ', admin) in the middle, so that all the API request (app-side) without cookie detection, and the admin request all need to go through the login detection operation, the entire middleware code is as follows:

function () {    returnfunction(req,res,next) {        if(Req.cookies.gid  NULL {            if(req.path! = "/admin/login" ) {                res.redirect ("/admin/login");            }            else{                next ();            }        }         Else {            next ();     }}}

3. Module reference
Express inside the module to each other to reference the visual and do not do anything to deal with, of course, the mutual reference must be my own code reasons.
Referring to each other's specific location forget where it is, but probably caused by articlemodule.js and favoritemodule.js, in the processing of MongoDB even table query when the problem. MongoDB even table is dejected, and later did not do even table, directly to the favorite operation records are add into a big table. The previous two years have been using MySQL or SQL Server, in the actual application of NoSQL spirit still did not understand, the design of the table when it is quite simple, the actual application found with MySQL, SQL Server is not a total, even the table, primary key, foreign keys are not.

Mode of 4.MVC
Now write a server not based on MVC are embarrassed to say that they are writing server. Express inside is still good, route, view, modules.
The route is a routing file that handles routing requests and calls the corresponding module function on request. All requests are done through req, res, next, and the internal functions are mostly callback-based. View under all the template files, in the course of the use of jade, the Smarty and other template language is not functional differences, mapping, distribution views, public modules, template inheritance, If-else and other logical judgments, all have, Jade's syntax has changed, not to write HTML tags, Node name, indent control level. Modules under the Custom prototype module, for example, there are a few module:ad, article, Word, user, etc. inside the module, introduced mongoose file to complete the deletion and deletion of the operation, add and delete to check the database function is asynchronous, So most of the functions under the file are also callback-based.
For example, api/worditem?id=5x23434fa5sk4dhid7a under API routing, gets the information of a sentence. In the Api.js:

/*sentences (ID) api/worditem?id=5x23434fa5sk4dhid7a*/Router.get ('/worditem ',function(req, res, next) {var_id =req.query.id; var_user = Req.query.uid | | -1; Word.findbyid (_id,function(err,data) {if(Err) {data._id=-1; } favorite.check ({t_id:data._id,user_id:_user},function(_f) {Data.flag=_f;        Res.send (data);    }); });});

Inside the Word.js:

//get Word entries by IDvarWord = Mongodb.mongoose.model ("word", Wordschema);varWordmodel =function(){};//...WordModel.prototype.findById =function(_id,callback) {varid = _id | | 1; Word.findone ({' _id ': id},function(err, obj) {varItemData = obj | | {_id:-1} ; Favorite.getcount ({t_id:itemdata._id},function(err,count) {Itemdata.favorite=count;        Callback (Err,itemdata);    }); });};

Route Judgment---Call the FindByID function of the word prototype---the findone operation of the Wordmodel encapsulated within the function, executes the callback after the query finishes, and passes the Err parameter and the data parameter to the callback function as a parameter.

5. File Upload
With the Multer middleware, the file storage location and the upload callback are processed directly through the JSON configuration.

App.use (Multer ({    ' public/upload/',    limits                : {2        , 5     },     function (file, req, res) {        true;         = file.name;    },    function  (Error, next) {        false;        = "";        Next (Error);})    );

To set the public folder as a static route:

App.use (Express.static (Path.join (__dirname, ' public '));

[Node.js]express+mongoose+mongodb's development notes

Related Article

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.