Express4+Mongodb極簡入門執行個體

來源:互聯網
上載者:User

標籤:

一、準備工作:

    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極簡入門執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.