node+express+mongodb,登陆代码备份二(+promise)(自用)

接上一篇文章

//index.js改为:
var express = require('express');
var router = express.Router();
var promise = require("promise");
var mp = require("mongodb");
//此处稳定版的node支持mongodb-promise

console.log('>>> a');
mp.MongoClient.connect("mongodb://127.0.0.1:27017/test").then(function(db){
    console.log('>>> b');
    Promise.resolve(db.collection('users')).then(function(user) {
        console.log('>>> c');
        router.get('/', function(req, res) {
            res.render('index', { title: 'index' });
        });

        /*login*/
        router.get('/login', function(req, res) {
            res.render('login', { title: 'login' });
        });

        /*logout*/
        router.get('/logout', function(req, res) {
            res.render('logout', { title: 'logout' });
        });

        /*hompage*/
        router.post('/homepage', function(req, res) {
            var query_doc = {userid: req.body.name, password: req.body.password};
            console.log(query_doc);
            user.findOne(query_doc).then(function(err, user){
                if(user !== null){
                    console.log(query_doc.userid + ": login success in " + new Date());
                    res.render('homepage', { title: 'homepage' });
                }else{
                    console.log(query_doc.userid + ": login failed in " + new Date());
                    res.redirect('/');
                }
            });
        });
    }, function(err) {
        console.log('>>> d',err);
    });
}, function(err) {
    console.log('>>> e',err);
});

module.exports = router;

你可能感兴趣的:(nodejs)