Basemongo base class Design

Source: Internet
Author: User
Tags findone

To further improve the application of the framework, this series of articles mainly introduces how to improve the architecture function, and how to use the architecture to do some specific application development. This series of courses can be found on GitHub, and links will be provided in each article.

This presentation is mainly about the design of the MONGO base class and its application. Please see the link below to download http://5xpan.com/fs/7hueanfgd6h350fe4/(download link has the benefit, please forgive have advertisement).
If you don't want to slow down, you can go straight to GitHub (HTTPS://GITHUB.COM/TNODEJS/BASEMONGODB)

Main function Structure Private method connection

The function is primarily to create a mongodb link and to cache the linked object.

 function connection(TableName, callback){        varConnect_url = Get_db_connect_url ();if(db_tmp[' DB ']) {db_tmp[' DB '].collection (TableName, function(err, collection){                if(ERR) {Console.log (' Basemongo can not connection with DB table error '); Process.Exit(1);            } callback (collection); });return; } mongoclient.connect (Connect_url, {native_parser:true}, function(err, db) {            if(ERR) {Console.log (' Basemongo can not connection with DB '); Process.Exit(1); } db_tmp[' DB '] = db;if(!tablename) {return; } db.collection (TableName, function(err, collection){                if(ERR) {Console.log (' Basemongo can not connection with DB table error '); Process.Exit(1);            } callback (collection);        });    }); }

This method calls the Get_db_connect_url method in this base class, primarily to get the DB connection character.

Get_db_connect_url

Gets the link string for the db, which is called primarily by connection.

functionGet_db_connect_url () {/*varDbconfig = Library.getconfig (' MongoDB ',' DB ');varHost = dbconfig[' Host '], port = dbconfig[' Port '], DbName = dbconfig[' db_name '], user = dbconfig[' user '], password = dbconfig[' Password ']; */varHost =' localhost ';varPort =' 27017 ';varuser ="';varPassword ="';varDbName =' Test_book ';if(!user &&!password) {return "mongodb://"+ Host +":"+ Port +"/"+ DbName; }return "mongodb://"+ user +":"+ Password +"@"+ Host +":"+ Port +"/"+ DbName; }

The method should read the configuration file, this part for the sake of easy to write directly in the function, readers use, use the Read configuration method to obtain.

Filter_options

For some basic operations in the query function sort, limit and skip to do a filter, unified processing logic.

 function filter_options(){        varFields =arguments[0] ?arguments[0] :NULL;varLimit =arguments[1] ?arguments[1] :0;varSort =arguments[2] ?arguments[2] :NULL;varSkip =arguments[3] ?arguments[3] :0;varoptions = {};if(Limit!==0) {options.limit = limit; }if(Skip!==0) {Options.skip = skip; }if(Fields)        {options.fields = fields; }if(sort)        {options.sort = sort; } options.timeout = timeout;returnOptions }
Get_result

Because MongoDB's base library returns very much data, this part is to do a layer of processing the data returned after the MongoDB operation, so that the outer call can clearly know the return result information.

/** * @desc to the MongoDB library back to do filter * * /function Get_result (Result) {if(!result[' Result ']){return false; }if(result[' Result '][' OK '] !=1){return false; }if(result[' Result '][' n '] <1){return false; }return true; }
Public method initconnecnt

This method initializes the MongoDB link object. In general, it is not necessary to call the function, but in special cases, the function can compensate for some of the simultaneous multiple requests caused by the bug problem. Specific words can be referred to my previous article, "node. js execution flowchart triggered thinking"

   /**     * @desc 初始化mongodb的连接对象     *     */    this.initConnecnt = function(){        connection(false, function(db){            DB_TMP[‘db‘] = db;        });    }
FindOne

Querying a single data record, returning only a single piece of data, and if no data is found to return null, the exception prints the error message and returns FALSE.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Condition Json Query criteria {' name ': 1}
Fields Json The Returned field {' _id ': 1, ' name ': 1}

For an example of a method, refer to Findone.js in source example

Find

Querying multiple data records, if no data is found to return null, the exception prints the error message and returns FALSE.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Condition Json Query criteria {' name ': 1}
Callback function callback function function (err, result) {}
Fields Json The Returned field {' _id ': 1, ' name ': 1}
Limit Int Returns the number of bars 5
Skip Int Number of skipped bars 5
Sort Json Sort fields {' name ': 1}
Insert

Inserts multiple data, returning the inserted data list.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Rowinfos Array Array of data inserted [{' name ': ' Danhuang '}]
Callback function callback function function (err, result) {}
Save

Inserts a single piece of data, returning the MONGO ID of the inserted data.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Rowinfo Json The inserted data {' name ': ' Danhuang '}
Callback function callback function function (err, result) {}
Remove (Findandremove)

Delete data, delete a single, or delete all eligible. The parentheses are queried and deleted.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Condition Json Query criteria {' name ': 1}
RemoveAll Boolean Delete all True
Callback function callback function function (err, result) {}
Update (findandmodify)

Updates a single piece of data, in parentheses, for query and modification.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Condition Json Query criteria {' name ': 1}
Rowinfo Json The inserted data {' name ': ' Danhuang '}
Update_set Boolean Whether to update locally True
Callback function callback function function (err, result) {}
UpdateAll

Update more than one data.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Condition Json Query criteria {' name ': 1}
Rowinfo Json The inserted data {' name ': ' Danhuang '}
Update_set Boolean Whether to update locally True
Callback function callback function function (err, result) {}
Count

Query the number of data that meets the criteria.

Parameter name parameter Type parameter Description parameter Examples
TableName String Table name of the action Book
Condition Json Query criteria {' name ': 1}
Callback function callback function function (err, result) {}
Example describes the data-tier action class

The class can be directly used as a data-tier operation class, and developers can invoke the module directly for development, such as the following code.
Data Insertion Example

Ar Basemongo =require('./basemongo ');varBasemongo =NewBasemongo ();varRowinfos = [{' name ':' Mongo2 ',' Test_url ':' http://blog.lovedan.cn ',' Download_book ':' http://download.lovedan.cn ',' Create_time ':New Date()    },    {' name ':' Mongo3 ',' Test_url ':' http://blog.lovedan.cn ',' Download_book ':' http://download.lovedan.cn ',' Create_time ':New Date()}];basemongo.insert (' book ', Rowinfos, function(Result){    if(false= = = result) {Console.log (' Insert error '); }Else{Console.log (result); }});

Sample Data Query

/* condition fields */var condition = {‘test_url‘‘http://blog.lovedan.cn‘};var fields    = {"create_time":0};/* test for find rowinfo */basemongo.find(‘book‘function(result){    if(false === result){        console.log(‘find error‘);    else {        console.log(result);    }}, fields);

And so on, please check the source code for the test.

As a base class

Of course, the module can also be used as a base class, providing other module layer class calls, as a parent class method, as shown in the example code below.

/** * * @type class * @author Danhuang * @time 2015-04-07 * @desc is mainly used for new book data */< /c0>varModel =require('. /.. /basemongo ');varSYS =require(' util '); function book(){    var_self = this;var_tablename =' T_book ';    Model.call (_self);    Sys.inherits (_self, Model); THIS.ADDDATAINDB = function(Rowinfo, callback){_self.save (_tablename, Rowinfo, function(ret){            if(ret)            {Callback (ret); }Else{Callback (false);    }        }); };}varBook =NewBook (); exports.adddataindb = book.adddataindb;

Then the above module layer class, can be directly called by the controller layer or other module layer, such as the downward use of the method.

varBook =require('./model_extended/book ');varRowinfo = {' name ':' node. js book ',' Author ':' Danhuang ',' desc ':' Good book ',' catalogue ': [' 1 ',' 2 '],' content ':' DASADASDASDASD ',' cover ':' http://blog.lovedan.cn ',' Pic_urls ':' http://download.lovedan.cn ',' Category_ids ': [' 1 ',' 2 '],' Pdf_url ':' http://download.lovedan.cn ',' Download_url ':' http://download.lovedan.cn ',' Download_tips ':' dddd ',' Buy_list ':' http://blog.lovedan.cn '};book.adddataindb (Rowinfo, function(ret){Console.log (ret);});

specifically to see which kind of need, if you think the base class to help you, help to register for the site, to the blogger to bring humble benefits.
Http://dd.ma/4hXDyCkp

Blog from: http://blog.lovedan.cn

Basemongo base class Design

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.