实现mongodb通讯

1 添加依赖项

"mongodb":"1.4.15",
"express-session": "1.9.1",
"connect-mongo": "0.4.1",
"connect-flash": "0.1.1"

其中connect-flash是用来记录登陆session消息的(不知道这样说对不对,因为还没仔细用上)

app.js

var express = require(‘express‘);
var path = require(‘path‘);
var favicon = require(‘serve-favicon‘);
var logger = require(‘morgan‘);
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: 1000 * 60 * 60 * 24 * 30},//30 days
    store: new MongoStore({
        db: settings.db,
        host: settings.host,
        port: settings.port
    })
}));

// view engine setup
app.set(‘views‘, path.join(__dirname, ‘views‘));
app.set(‘view engine‘, ‘ejs‘);
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 handler
app.use(function (req, res, next) {
    var err = new Error(‘Not Found‘);
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get(‘env‘) === ‘development‘) {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render(‘error‘, {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 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‘, {title: ‘主页‘});
    });
    app.get(‘/reg‘, function (req, res) {
        res.render(‘reg‘, {title: ‘注册‘});
    });

    app.get(‘/login‘, function (req, res) {
        res.render(‘login‘, {title: ‘登录‘});
    });
    app.post(‘/login‘, function (req, res) {
    });
    app.get(‘/post‘, function (req, res) {
        res.render(‘post‘, {title: ‘发表‘});
    });
    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‘];
        //检验用户两次输入的密码是否一致
        if (password_re != password) {
            req.flash(‘error‘, ‘两次输入的密码不一致!‘);
            return res.redirect(‘/reg‘);//返回注册页
        }
        //生成密码的 md5 值
        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
        });
        //检查用户名是否已经存在
        User.get(newUser.name, function (err, user) {
            if (err) {
                req.flash(‘error‘, err);
                return res.redirect(‘/‘);
            }
            if (user) {
                req.flash(‘error‘, ‘用户已存在!‘);
                return res.redirect(‘/reg‘);//返回注册页
            }
            //如果不存在则新增用户
            newUser.save(function (err, user) {
                if (err) {
                    req.flash(‘error‘, err);
                    return res.redirect(‘/reg‘);//注册失败返回主册页
                }
                req.session.user = user;//用户信息存入 session
                req.flash(‘success‘, ‘注册成功!‘);
                res.redirect(‘/‘);//注册成功后返回主页
            });
        });
    });
};

setting.js (根目录)

/**
 * 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;

//存储用户信息
User.prototype.save = function(callback) {
    //要存入数据库的用户文档
    var user = {
        name: this.name,
        password: this.password,
        email: this.email
    };
    //打开数据库
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);//错误,返回 err 信息
        }
        //读取 users 集合
        db.collection(‘users‘, function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);//错误,返回 err 信息
            }
            //将用户数据插入 users 集合
            collection.insert(user, {
                safe: true
            }, function (err, user) {
                mongodb.close();
                if (err) {
                    return callback(err);//错误,返回 err 信息
                }
                callback(null, user[0]);//成功!err 为 null,并返回存储后的用户文档
            });
        });
    });
};

//读取用户信息
User.get = function(name, callback) {
    //打开数据库
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);//错误,返回 err 信息
        }
        //读取 users 集合
        db.collection(‘users‘, function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);//错误,返回 err 信息
            }
            //查找用户名(name键)值为 name 一个文档
            collection.findOne({
                name: name
            }, function (err, user) {
                mongodb.close();
                if (err) {
                    return callback(err);//失败!返回 err 信息
                }
                callback(null, user);//成功!返回查询的用户信息
            });
        });
    });
};

 

)

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。