Implementing MongoDB Communication

Source: Internet
Author: User
Tags md5

1 adding dependencies

"MongoDB": "1.4.15", "express-session": "1.9.1", "Connect-mongo": "0.4.1", "Connect-flash": "0.1.1"

Where Connect-flash is used to record the login session (I do not know if it is right, because it is not carefully used)

App.js

var express = require (' Express '), var path = require (' path '), var favicon = require (' Serve-favicon '); var logger = require (' m Organ '), var cookieparser = require (' Cookie-parser '), var bodyparser = require (' Body-parser '), var routes = require ('./ Routes/index '); var users = require ('./routes/users '); var settings = require ('./settings ');//var app = Express (); var Session = require (' express-session '), var mongostore = require (' Connect-mongo ') (session), App.use (session ({resave: False, Saveuninitialized:true, Secret:settings.cookieSecret, Key:settings.db,//cookie name Cookie: {maxAge:        30},//30 days Store:new mongostore ({db:settings.db, host:settings.host, Port:settings.port}));//View engine Setupapp.set (' views ', Path.join (__dirname, ' views ')); App.set (' View engine ', ' E JS '), var flash = require (' Connect-flash '); App.use (Flash ());//Uncomment after placing your favicon in/public//app.use ( Favicon (__dirname + '/public/favicon.ico ')); aPp.use (Logger (' dev ')); App.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ({extended:false})); App.use ( Cookieparser ()); App.use (Express.static (Path.join (__dirname, ' public '));//app.use ('/', routes);//app.use ('/users ', users '); Routes (app);//catch 404 and Forward to error handlerapp.use (function (req, res, next) {var err = new Error (    ' Not Found ');    Err.status = 404; Next (err);}); /error handlers//development error handler//would print Stacktraceif (App.get (' env ') = = = ' Development ') {App.use (fun        Ction (Err, req, res, next) {Res.status (Err.status | | 500);    Res.render (' error ', {message:err.message, error:err}); });} Production error handler//no stacktraces leaked to Userapp.use (function (err, req, res, next) {Res.status (err.stat US | |    500); Res.render (' error ', {message:err.message, error: {}}); Module.exports = app;

Index.js

var crypto = require (' crypto '), User = require ('. /models/user.js '); module.exports = function (APP) {app.get ('/', function (req, res) {res.render (' index ', {TITL    E: ' Home '});    });    App.get ('/reg ', function (req, res) {Res.render (' reg ', {title: ' Register '});    });    App.get ('/login ', function (req, res) {res.render (' login ', {title: ' Login '});    });    App.post ('/login ', function (req, res) {});    App.get ('/post ', function (req, res) {Res.render (' post ', {title: ' Publish '});    });    App.post ('/post ', function (req, res) {});    App.get ('/logout ', function (req, res) {});            App.post ('/reg ', function (req, res) {var name = req.body.name, password = Req.body.password,        Password_re = req.body[' password-repeat '];            Verify that the password entered by the user two times is consistent if (password_re! = password) {req.flash (' error ', ' two times entered password is inconsistent! '); Return Res.redirect ('/reg ');//Return to registration page}//Generate password MD5 value var MD5 = CRYPTO.CREatehash (' MD5 '), password = md5.update (Req.body.password). Digest (' Hex ');         var newuser = new User ({name:name, Password:password, email:req.body.email}); Check if the user name already exists user.get (newuser.name, function (err, user) {if (err) {Req.flash (                ' ERROR ', err);            return Res.redirect ('/');                } if (user) {Req.flash (' error ', ' Users already exist! ');                Return Res.redirect ('/reg ');//returns to registration page}//If not present, add user Newuser.save (function (err, user) {                    if (err) {Req.flash (' error ', err);                Return Res.redirect ('/reg ');//registration failed to return to the main album} Req.session.user = user;//user information stored in session                Req.flash (' success ', ' registered successfully! ');        Res.redirect ('/');//return home after successful registration);    }); });};

Setting.js (root directory)

/** * Created by Administrator on 2015/3/31. */module.exports = {    cookiesecret: ' MyBlog ',    db: ' blog ',    host: ' localhost ',    port:27017};

Db.js (Models

/** * Created by Administrator on 2015/3/31. */var settings = require ('.. /settings '),    Db = require (' MongoDB '). Db,    Connection = require (' MongoDB '). Connection,    Server = require (' MongoDB '). Server;module.exports = new Db (settings.db, New Server (Settings.host, Settings.port),    {safe:true});

User.js (models)

/** * Created by Administrator on 2015/3/31.    */var MongoDB = require ('./db '); function user (user) {this.name = User.Name;    This.password = User.password; This.email = User.email;}; Module.exports = user;//Store user Information User.prototype.save = function (callback) {//user document to be stored in the database var user = {Name:thi    S.name, Password:this.password, email:this.email};        Open Database Mongodb.open (function (err, db) {if (err) {return callback (ERR);//error, Return err information} Read the Users Collection db.collection (' Users ', function (err, collection) {if (err) {MongoDB.                Close ();                Return callback (ERR);//error, return ERR message}//insert user data into the Users collection Collection.insert (user, {                Safe:true}, function (err, user) {mongodb.close (); if (ERR) {return callback (ERR);//error, return ERR message} callback (NULL, user[0]);Success!        ERR is null and returns the stored user's document});    }); });};/            /read user Information User.get = function (name, callback) {//Open database Mongodb.open (function (err, db) {if (err) {  Return callback (ERR);//error, return ERR message}//Read Users collection db.collection (' Users ', function (err, collection)                {if (err) {mongodb.close ();                Return callback (ERR);//error, return ERR message}//Find user name (name key) value for name a document Collection.findone ({                Name:name}, function (err, user) {mongodb.close (); if (ERR) {return callback (ERR);//Failed! Returns the ERR message} callback (null, user);//success!        Returns the user information of the query});    }); });};

)

Implementing MongoDB Communication

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.