Encapsulation of NODE-MONGODB linked database functions

Source: Internet
Author: User
Tags mongoclient

The code is as follows:

Create the Database.js file in a separate directory, named model.

/**
* Created by pi on 2016/9/5.
*/

functionOpenDatabase (DatabaseName,CollectionName,FN) {
VarMongoclient=Require' MongoDB ').Mongoclient;
VarDb_str="Mongodb://localhost:27017/"+DatabaseName;
Mongoclient.ConnectDB_STR,functionErrDB) {
IfERR) throw err;
Console. log ("database connection succeeded! ");
var c1=db. Collection (collectionname);
fn (C1); callback function
})
}
module. exports=opendatabase;

This can be referenced in a file that requires linked data:
/**
* Created by pi on 2016/9/5.
*/
ConstConnect=Require'./model/database ');
Connect' Student ',' Student ',functionDB) {
Db. find ({},{_id:0}). ToArray (function (err,Res) {
if (err) throw err;
Console. log (res);
});
Db.close ();//Shut down the database as required
});

I'm using the form of a callback function to manipulate the asynchronous link database operation.
In the Model folder, according to the requirements of each document operation into the asynchronous package, adding and removing the basic operation of the Change check
This only solves the database connection problem in the form of a callback function.
Most of the time did not find a synchronous connection to the database method, a bit depressed, only this stupid method.

If you see, look forward to your guidance

Encapsulation of NODE-MONGODB linked database functions

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.