Application Mongoose Development MongoDB (3) Controller (controllers)

Source: Internet
Author: User
Tags node server

The basic composition of the controller and how to call it via routing

In the controller, through the establishment of functions and export, the front-end to the database query, new, delete and modify the requirements, and make it can be called in the route, complete the encapsulation of the API. This paper focuses on the relationship between structures, and the specific problem solving methods will be given in the following article.

The following code is a simple but complete controller file, named Comment_controller.js, stored under the ~/controllers folder:

var   config = require ('.. /config '),         Comment = require ('.. /models/comment '); Based on Doctorid query related evaluation 2017-03-30 Gyexports.getcommentsbydoc = function (req, res) {         //Query condition         var doctorobject = Req.body.doctorObject;         var query = {doctorid:doctorobject._id};         Set the parameter         var opts = ';         var fields = {' _id ': 0, ' Revisioninfo ': 0};         var populate = {path: ' Patientid ', select:{' _id ': 0, ' Revisioninfo ': 0}};          Comment.getsome (query, function (err, item) {                   if (err) {                    return Res.status ($). Send (Err.errmsg);             }             Res.json ({results:item});         }, OPTs, fields, populate);}

  

First, declare some constants that are used, including global settings and data models that need to be called.

Then the method is established and exported, note that when the function is established, the incoming parameter is req, Res. Where req is the input parameter, and when using the Get method (or some post methods), The parameters in the URL are passed through Req.query, and in the Post method, the parameters in the body are passed through req.body. Res is a return parameter and is typically returned in two ways:

Status Code plus information: (return Res.status (+). Send (ERR.ERRMSG))

or JSON format: (Return Res.json (Result: ' error! ') )

If you want the exported function to be reused in a combination of different routes, that is, to invoke multiple functions using a single route, it is necessary to allow the preceding export function to proceed to the next step, which requires adding a next in the passed parameter and allowing the next position in the function to use the next () function.

Still take this function as an example, how to call in the route?

The ~/routes/routes.js file mentioned in the 1th article:

self-defined configurationsvar config = require ('.. /config '); Middlewares//declares the Middleware collection//controllers//Declaration Controller Collection var Doctorctrl = require ('. /controllers/doctor_controller '); Add the function declared in comment_controller.js var Commentctrl = require ('.. /controllers/comment_controller '); Module.exports = function (app, webentry) {app.get ('/', function (req.res) {    res.send (' Server Root ');});// Set the route path and path required to call the function or combination app.post ('/doctor/postdocbasic ', doctorctrl.insertdocbasic); App.get ('/doctor/getdoctorinfo ', Doctorctrl.getdoctorobject, Doctorctrl.getcomments, doctorctrl.getdoctorinfo)//...//Set method Routing and functions to be called app.get ('/ Comment/getcomments ', Doctorctrl.getdoctorobject, Commentctrl.getcommentbydoc); };

  


For ease of understanding, attach the code about Doctorctrl.getdoctorobject:

Doctor_controller.jsvar config = require ('.. /config '); var Doctor = require ('.. /models/doctor ');//through Doctor table userid query _id 2017-03-30 gy//Modify: Increase the judgment does not exist ID situation 2017-04-05 Gyexports.getdoctorobject = Function (req, res, next) {         if (req.query.userId = = NULL | | req.query.userId = = ") {                   return Res.json ({result: ' Please fill in Userid! '});    var query = {        userId:req.query.userId    };    Doctor.getone (query, function (err, Doctor) {        if (err) {            console.log (err);            Return res.status. Send (' server error, user query failed! ');        }        if (doctor = = null) {                 return Res.json ({result: ' nonexistent Doctor id! '});        Req.body.doctorObject = Doctor;        Next ();    });};

  


The purpose of this code is to enter the UserID query in the Doctor table to the corresponding entry and pass the information into the req.body.doctorObject. As you can guess, this code is reusable. Of course, this code reuse situation will be more limited, because it is rough, on this point, the following will give a more comprehensive code of reuse.

To run the command line in the project folder, run the command:

Node Server.js

If there are no errors, the following prompt is available:

The hint content is defined in Server.js.

To test whether the API is available, it is recommended to use the Postman app (Google store download). Enter the URL in the request box:

Localhost:4050/comment/getcomments

Click the params input key and value, then the request becomes:

Localhost:4050/comment/getcomments?userid=doc01

Click Send to send the request waiting to return, if all goes well, there will be similar return:

If it is a post and other methods that need to be entered in body, select the following body, raw, and change the later format to JSON:

Note that port 4050 is defined in Setting.js, please refer to the 1th article in this series.

If you are testing a local project, you can use localhost directly, and if you are testing a project deployed on another computer or server, replace localhost with the IP address of the corresponding computer or server.

Apply Mongoose to develop MongoDB (3) Controller (controllers)

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.