nodejs 學習(4) express+mongoose

1、關於安裝和啓動:html

一、設置環境變量:D:\Program Files\MongoDB\binweb

二、啓動時須要cd到bin 目錄,而後 mongod --dbpath "D:\mongdb\data"設置數據庫存儲路徑mongodb

2、例子(登陸註冊表單)數據庫

1express


2 index.jsjson

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 模板 (注意縮進)cookie

3.1 layout.jadesession

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

3.2 index.jadeapp

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.jademongoose

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
相關文章
相關標籤/搜索