NODE14---Hierarchical database operations

Source: Internet
Author: User
Tags mongoclient

/**0. Where the outer function is called, it must be the outer function body executed first, the callback function is the same as the normal function address, and then see the function body to specify how the callback function executes. 1. The callback function is used asynchronously, 2. The callback function can also be seen as extending the function body, because the callback function can be different, the rest is a common function. 3. callback function intermediary function, the place where the function is called and where the function is defined, the data can be transferred .*/varExpress = Require ("Express");varApp =Express ();vardb = require ("./model/db.js");//inserting data, using our own encapsulated DB module, is DAO. App.get ("/charu",function(req,res) {//three parameters, to which set to increase, add what, add after what to doDb.insertone ("Teacher", {"name": "Little Red"},function(err,result) {if(Err) {Console.log ("Insert Failed"); return; } res.send ("Insert Succeeded");    }); /*Insertone = function (CollectionName, JSON, callback) {_connectdb (function (err, db) {Db.collection (CO            Llectionname). Insertone (JSON, function (err, result) {callback (err, result); Db.close ();    Close database})}; */});//FindApp.get ("/du",function(req,res) {//This page now accepts a page parameter.     varpage = parseint (req.query.page);//It's easy to read the get parameters in Express    //Find 4 parameters, in which set to check, what to check, paging setup, after checking what to doDb.find ("Canguan", {},{"Pageamount": 6, "page":p Age},function(Err,result) {//First, execute the Find function body, when the function of this special parameter depends on how the function body is written,        if(Err) {Console.log (err);        } res.send (Result);    Console.log (result.length); });});//DeleteApp.get ("/shan",function(req,res) {varBorough =Req.query.borough; Db.deletemany ("Canguan", {"Borough": Borough},function(Err,result) {//executes the Deletemany function body first, when the function executes depends on the function body       if(Err) {Console.log (err);    } res.send (Result); });});//ModifyApp.get ("/xiugai",function(req,res) {Db.updatemany ("Canguan",//Set name        {            "Borough": "Manhattan"//change what?}, {$set: {borough:"Beijing"}//How to change        },        function(Err,result) {//What do you do after you change?            if(Err) {Console.log (err);        } res.send (Result); }    );}); App.listen (3000);

Db.js

/** * The callback function is considered to be a normal function address. *///This module encapsulates all the common operations on the database .varMongoclient = require (' MongoDB '). mongoclient;varSettings = require (".. /settings.js ");//regardless of the database operation, are connected to the database first, so we can connect the database//encapsulation becomes an intrinsic functionfunction_connectdb (callback) {//executing the _CONNECTDB function body first determines when the function is executed    varurl = settings.dburl;//from the settings file, the database address    //connecting to a databaseMongoclient.connect (URL,function(err, db) {if(Err) {callback (Err,NULL); return;    } callback (err, DB); });}//Insert data, open Close database every timeExports.insertone =function(CollectionName, JSON, callback) {_connectdb (function(Err, DB) {//executes the _CONNECTDB function body first, when the function is executed depending on the function bodyDb.collection (CollectionName). Insertone (JSON,function(err, result) {callback (err, result); Db.close (); //Close the database        })    })};//find the data and find all the data. Args is an object {"Pageamount": Ten, "Page": Ten}Exports.find =function(CollectionName, JSON, C, D) {//JS does not have a function overload, it must be modified by parameters.     varresult = [];//result Array    if(Arguments.length = = 3) {        //then the parameter C is callback, and parameter d is not passed.         varcallback =C; varSkipnumber = 0; //Number Limit        varLimit = 0; } Else if(Arguments.length = = 4) {        varcallback =D; varargs =C; //number of bars that should be omitted        varSkipnumber = Args.pageamount * args.page | | 0; //Number Limit        varLimit = Args.pageamount | | 0; //Sorting Method        varSort = Args.sort | | {}; } Else {        Throw NewError ("The Find function has a number of arguments, 3, or 4.") "); return; }    //Connect to the database, and then find all_connectdb (function(Err, DB) {//executes the _CONNECTDB function body first, when the function is executed depending on the function body        varcursor =db.collection (CollectionName). Find (JSON). Skip (Skipnumber). Limit. Sort (sort); Cursor.each (function(err, doc) {if(Err) {callback (Err,NULL); Db.close (); //Close the database                return; }            if(Doc! =NULL) {Result.push (doc); //put into the result array}Else {                //The traversal is over, no more documents.CallbackNULL, result); Db.close (); //Close the database            }        }); });}//DeleteExports.deletemany =function(CollectionName, JSON, callback) {_connectdb (function(err, db) {//Deletedb.collection (CollectionName). Deletemany (JSON,function(err, results) {callback (err, results); Db.close (); //Close the database            }        ); });}//ModifyExports.updatemany =function(CollectionName, Json1, Json2, callback) {_connectdb (function(err, db) {db.collection (CollectionName). Updatemany (Json1, Json2,function(err, results) {callback (err, results);            Db.close ();    }); })}exports.getallcount=function(collectionname,callback) {_connectdb (function(err, db) {db.collection (CollectionName). Count ({}). Then (function(count) {callback (count);        Db.close ();    }); })}

Settings.js

/** *=    {"Dburl": "Mongodb://localhost:27017/haha"}

NODE14---Hierarchical database operations

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.