標籤:
一、準備工作:
1、啟動mongodb:bin目錄下運行
2、在test資料庫裡插入一條資料:
二、正式開始:
1、通過應用產生器工具 express 快速建立一個應用的骨架,參考Express中文網http://www.expressjs.com.cn/starter/generator.html;
2、這裡我建立了一個名叫firstapp的應用:
通過Express產生器就快速產生了如下的應用骨架:
3、express4預設以jade為模板,這裡我改用ejs,在package.json檔案中的dependencies增加"ejs": "*",這裡一併把"mongoose":"*"也添加進來。註:*號會告訴NPM“安裝最新版本”。
修改後的檔案內容就是這樣的:
4、接下來就是修改views裡的內容,刪掉預設的jade檔案,增加index.ejs:
<!DOCTYPE html><html><head> <title><%= title %></title></head><body> <p>Hi, <%= user.username %></p></body></html>
這裡增加一個error頁error.ejs,報錯時可以看到錯誤資訊
<!DOCTYPE html><html><head> <title>error</title></head><body><h1><%= message %></h1><h2><%= error.status %></h2><pre><%= error.stack %></pre></body></html>
5、修改路由檔案routes/index.js:
var express = require(‘express‘);var router = express.Router();var mongoose = require(‘mongoose‘), Schema = mongoose.Schema;var uri = ‘mongodb://localhost/test‘;var db = mongoose.createConnection(uri);var User = new Schema({ id : {type: String, index: true }, username : {type: String }, age : {type: String }});/* GET users listing. */router.get(‘/‘, function(req, res, next) { db.model(‘user‘, User).findOne({username:"charles"}, function (err, user) { res.render(‘index‘, {title: ‘Express‘, user: user }); });});module.exports = router;
這裡我串連的是test資料庫。
6、至此就可以install下載相關包就可以運行了。
運行完後工程裡就多了node_modules檔案夾,下載好了mongoose、ejs等需要用到的模組。
7、執行:,在瀏覽器裡輸入http://localhost:3000/就可以看到結果了。
Express4+Mongodb極簡入門執行個體