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