nodejs 学习(4) express+mongoose

一、关于安装和启动:

1、设置环境变量:D:\Program Files\MongoDB\bin

2、启动时需要cd到bin 目录,然后 mongod --dbpath "D:\mongdb\data"设置数据库存储路径

二、例子(登录注册表单)

1


2 index.js

var express=require("express"),
    bodyParser=require('body-parser'),
    multer=require('multer'),
    mongoose=require('mongoose'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    app=express();


var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my-website');
db = mongoose.connection;
db.once('open', function callback () {
  console.log("yah");
}); 
var kittySchema = mongoose.Schema({
 first: String,
 last: String,
 email: {type:String,unique:true},
 password:{type:String,index:true}
});
var User = mongoose.model('user', kittySchema);


app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.use(cookieParser());
app.use(session({
  secret: 'my secret',
  resave: false,
  saveUninitialized: true
}));


app.set("view engine","jade");


app.use(function(req,res,next){
    if(req.session.loggedIn){
        res.locals.authenticated=true;
        User.findById(req.session.loggedIn,function(err,doc){

            if(err){
                return next(err);
            }
            if(doc){
                res.locals.me=doc;
            }
            next();
        });
    }else{
        res.locals.authenticated=false;
        next();
    }
});

app.get("/",function(req,res){
    res.render('index');
});

app.get("/login",function(req,res){
    res.render("login");
})


app.get("/signup",function(req,res){
    res.render("signup");
});

app.post("/signup",function(req,res,next){
    var user = new User(req.body.user);
    user.save(function(err){
        if(err) return next(err);
        res.redirect("/login/"+user["email"]);
    });
});

app.get("/login/:signupEmail",function(req,res){
    res.render('login',{signupEmail:req.params.signupEmail});
});

app.post("/login",function(req,res){
    User.findOne({"email":req.body.user.email,"password":req.body.user.password},function(err,doc){
         if(err){
             return next(err);
         }
         if(!doc){
             return res.send("<p>User not found.Go back and try again</p>");
         }
         var sess=req.session;
         req.session.loggedIn=doc._id.toString();
         res.redirect("/");
    });
});

app.get("/logout",function(req,res){
    var sess=req.session;
    req.session.loggedIn="",
    res.redirect("/");
});

app.listen(3000,function(){
    console.log("app listening on *:3000");
});

3 模板 (注意缩进)

3.1 layout.jade

doctype html
html
    head
        title MongoDB example
    body
        h1     My first MongoDB app
        hr
        block body

3.2 index.jade

extends layout
block body
    if (authenticated)
        p Welcome back,#{me.first}
        a(href="/logout") Logout
    else
        p Welcome new visitor!
        ul
            li: a(href="/login") Login
            li: a(href="/signup") Signup

3.3 login.jade

extends layout
block body
    form(action="/login",method="POST")
        fieldset
            legend Log in
            if(signupEmail)
                p 
                    Congratulations on signing up! Please login below.
                    input(name="user[email]",type="text",value=signupEmail)
            else
                p
                    label Email
                    input(name="user[email]",type="text")
            p
                label Password
                input(name="user[password]",type="password")
            p
                button Submit
            p
                a(href="/") Go back

3.4 signup.jade

extends layout
block body
    form(action="/signup",method="POST")
        fieldset
            legend Sign 
            p
                label First
                input(name="user[first]",type="text")
            p
                label last
                input(name="user[last]",type="text")
            p
                label Email
                input(name="user[email]",type="text")
            p
                label Password
                input(name="user[password]",type="password")
            p
                button Submit
            p
                a(href="/") Go back

 

posted on 2015-01-21 15:01  叫我钱了个浅  阅读(346)  评论(0编辑  收藏  举报

导航