DAO is the way the database is provided and then encapsulates one layer.
Mongodb-dao:
varMongoclient=require ("MongoDB"). mongoclient;//Database ConnectionvarSetting=require (".. /settings.js ");//Connect Database methodsfunction_connectdb (callback) {varUrl=Setting.dburl; Mongoclient.connect (URL,function(err,db) {if(Err) {callback (Err,NULL); return ; } callback (ERR,DB); });}//Inserting DataExports.insertone=function(collectionname,json,callback) {_connectdb (function(err,db) {db.collection (CollectionName). Insertone (JSON,function(Err,result) {callback (Err,result); Db.close (); }); });}//Find DataExports.find=function(collectionname,json,c,d) {varresult=[]; varargslen=arguments.length; varLimit=0; varSkipnum=0; varcallback=C; varsort={}; if(argslen==4){ varargs=C; Callback=D; Limit=args.pageamount| | 0; Skipnum=args.pageamount*args.page| | 0; Sort=args.sort| |{}; } _connectdb (function(err,db) {if(Err) {res.send (err); return ; } varCursor=db.collection (CollectionName). Find (JSON). Limit (limit). Skip (Skipnum). Sort (sort); Cursor.each (function(err,doc) {if(Err) {callback (Err,NULL); Db.close (); return ; } if(doc!=NULL) {Result.push (doc); }Else{callback (Err,result); Db.close (); } }); });}//Deleteexports.deletemany=function(collectionname,json,callback) {_connectdb (function(err,db) {db.collection (CollectionName). Deletemany (JSON,function(Err,result) {callback (Err,result); Db.close (); }) });}//Updateexports.updatamany=function(collectionname,json1,json2,callback) {_connectdb (function(err,db) {db.collection (CollectionName). Updatamany (Json1,json2,function(Err,result) {callback (Err,result); Db.close (); }) });}//get aggregate Data totalExports.getallcount=function(collectionname,callback) {_connectdb (function(err,db) {db.collection (CollectionName). Count (). Then (function(count) {callback (count); Db.close (); }); });}
Settings.js:
module.exports={ "Dburl": "Mongodb://localhost:27017/tab"}
Here is an example of login-registration-message:
varExpress=require ("Express");varapp=Express ();varDb=require ("./model/mdb.js");/*formidable must be a class form submission, direct Ajax not, such as using AJAX to submit a form*/varFormidable=require ("Formidable");/** * MongoDB can create a library directly, as long as the library does not exist it will be created, when it is present, use the current collection is also, so it is flexible, is a can use JS to write the shell database it does not value the consistency of the field, so it can be stored in the document under each set of J The object in the Son object has a _id that can be used to make a unique identifier because it is an object, it needs some special way to convert it, such as the Require ("MongoDB") in Nodejs. ObjectID introduces a module object to convert it directly*/varObjectid=require ("MongoDB"). ObjectID;varSession = Require ("Express-session");varMD5 = require ('./model/md5.js '));//session default settings only req have session settings and getApp.use (Session ({secret:' Keyboard Cat ', Resave:false, saveuninitialized:true}));//referencing the rendered page engineApp.set ("View Engine", "Ejs");//Static file LocationApp.use (Express.static ("./public"));//entranceApp.get ("/",function(req,res,next) {if(!Req.session.login) {Res.redirect ("/zhuce"); return ; } //Query The total amount of dataDb.getallcount ("Liuyanban",function(count) {Res.render ("Index", {Pageamount:Math.ceil (Count/5),name:req.session.username}); });});//SubmitApp.post ("/tijiao",function(req,res,next) {varform=NewFormidable. Incomingform (); Form.parse (req,function(err,fields) {Db.insertone ("Liuyanban",{ "Name": Fields.name,"Des": Fields.des,"Time":NewDate ()},function(err,result) {if(Err) {Res.send (false); return ; } res.send (true); }); });});//EnquiryApp.get ("/read",function(req,res,next) {varpagenum=parseint (Req.query.pageNum); Db.find ("Liuyanban", {},{pageamount:5, Page:pagenum, Sort:{time:-1} },function(err,result) {varObj={status:false}; if(Err) {res.send (obj); return ; } obj["Status"]=true; obj["Content"]=result; Res.send (obj); });});//DeleteApp.get ("/shanchu",function(req,res,next) {varId=ObjectID (req.query.id); Db.deletemany ("Liuyanban", {_id:id},function(err,result) {if(Err) {Res.send ("Delete Failed"); return ; } res.redirect ("/"); });});//RegisterApp.post ("/zhuce",function(req,res,next) {varform=NewFormidable. Incomingform (); Form.parse (req,function(err,fields) {Db.insertone ("User",{ "Name": Fields.name,"PWD": MD5 (FIELDS.PWD)},function(err,result) {if(Err) {Res.send (false); return ; } res.send (true); }); });});//RegisterApp.get ("/zhuce",function(Req,res,next) {Res.render ("Zhuce");});//LoginApp.post ("/denglu",function(req,res,next) {varform=NewFormidable. Incomingform (); Form.parse (req,function(err,fields) {varPwd=MD5 (FIELDS.PWD); Db.find ("User", {name:fields.name},function(err,result) {varobj={}; if(Err) {res.send (obj); return ; } if(result.length==0) {obj={status:false, err: "Account Error"}; Res.send (obj); return ; } if(pwd!=result[0].pwd) {obj={status:false, err: "Bad password"}; Res.send (obj); return ; } req.session.login=true; Req.session.username= Result[0].name; obj["Status"]=true; obj["Content"]=result; Res.send (obj); }); });});//LoginApp.get ("/denglu",function(Req,res,next) {Res.render ("Denglu");}); App.listen (3000);
The directory structure is not given. Because the structure is the default setting of that kind.
MD5:
var crypto = require (' crypto '); function MD5 (str) { var md5method=crypto.createhash ("MD5"); var pwd=md5method.update (Str.tostring ()). Digest ("base64"); return pwd;} function DealMd5 (str) { return MD5 (MD5 (STR). substr (2,5) +md5 (str) +md5 (str). substr (4,7));} Module.exports=dealmd5;
Open the database every time you use MongoDB.
Normal Open
Mongod--dbpath C:\mongo
Select engine turned on because two engines appeared after mongodb3, and some of the new engines were not compatible with MONGODB clients
Mongod--storageengine Mmapv1--dbpath C:\mongo
Node's MongoDB DAO