Node.js 入門:Express + Mongoose 基礎使用

原文地址:http://blog.gdfengshuo.com/2017/07/29/20html

前言

Express 是基於 Node.js 平臺的 web 應用開發框架,在學習了 Node.js 的基礎知識後,可使用 Express 框架來搭建一個 web 應用,實現對數據庫的增刪查改。node

數據庫選擇 MongoDB,它是一個基於分佈式文件存儲的開源數據庫系統,Mongoose 是 MongoDB 的對象模型工具,能夠在異步環境裏工做。jquery

接下來就使用 Express + Mongoose 來實現簡單的增刪查改,在實現的過程當中來學習 Express 和 Mongoose 的基礎知識。git

原文做者:林鑫,做者博客:http://blog.gdfengshuo.com/github

準備

既然是基於 Node.js 的框架,那麼確定須要裝 node.js,還有 MongoDB,網上有不少安裝教程。而後使用 express-generator 來快速生成一個 Express 項目。那麼先安裝一下 express-generatorweb

npm install -g express-generator

而後初始化一個名爲 express-demo 的項目ajax

express express-demo

目前 Express 已經發布到了 4.x 版本,接下來也是基於這個版原本實現的。mongodb

cd express-demo
npm install
npm start

瀏覽器打開 http://localhost:3000 ,就能夠看到已經能夠訪問了。數據庫

目錄

├─bin/      // 啓動文件
├─public/   // 資源文件
├─routes/   // 路由
├─views/    // 視圖
├─app.js
└─package.json

初始化的項目目錄簡單明瞭,接下來咱們來看看 app.js 裏是寫了什麼。express

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

這是設置模板引擎,使用了 jade 模板引擎,views/ 目錄下都是 .jade 格式文件,這種寫法我並不熟悉,那麼來改一下,改爲 ejs 引擎,.html 格式的視圖文件。(須要 npm 安裝 ejs 模塊)

var ejs = require('ejs');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', ejs.__express);
app.set('view engine', 'html');

實現

以上準備都好了以後,咱們就來看看如何實現用戶信息的增刪查改。這裏咱們先把視圖和路由搭建起來,能訪問頁面以後再來實現數據庫操做的功能。

用戶列表

在 view/ 視圖目錄下建立如下文件: UserList.html

<!DOCTYPE html>
<html>
<head>
    <title>用戶列表頁面</title>
</head>
<body>
    <table>
        <tr>
            <th>用戶名</th>
            <th>郵箱</th>
            <th>操做</th>
        </tr>
        <% for(var i in user){ %>
            <tr>
                <td><%= user[i].username %></td>
                <td><%= user[i].email %></td>
                <td>
                    <div>
                        <a href="/users/detail/<%= user[i]._id %>"> 查看 </a>
                        <a href="/users/edit/<%= user[i]._id %>"> 編輯 </a>
                        <a href="#" class="del" data-id="<%= user[i]._id %>"> 刪除 </a>
                    </div>
                </td>
            </tr>
        <% } %>
    </table>
</body>
</html>

<% %> 就是 ejs 模板引擎的語法,user 是在路由渲染頁面的時候傳過來的,它是如何傳的,待會再看。
接下來實現上面視圖對應的路由,項目中默認已經給咱們生成了兩個路由。在 routes/ 路由目錄下已經有了兩個路由文件:index.js 和 users.js。

app.js 中,已經幫咱們設置好了這兩個路由:

var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/users', users);

只要瀏覽器訪問 http://localhost:3000/users ,就能訪問到 users 對應的頁面了。咱們來看看路由裏 users.js 是如何寫的。

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

express.Router 類建立模塊化、可掛載的路由句柄。咱們修改上面代碼來建立用戶列表的路由 users/list

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/list', function(req, res, next) {
  var list = [{_id: 1, username: 'linxin', email: '123123@qq.com'}];
  res.render('UserList',{
      user: list
  })
});

module.exports = router;

還記得在 UserList.html 視圖中的 user 變量嗎,這裏用到了 res.render() 響應方法,功能就是渲染視圖模板,第一個參數爲視圖文件名,第二個參數爲對象,用於向模板中傳遞數據,user 就是在這裏傳過去的。更改完路由以後重啓服務器,訪問 http://localhost:3000/users/list 就能夠看到用戶列表頁面了。

可是這用戶信息是寫死的,要怎麼從數據庫中讀取呢?

鏈接數據庫

咱們這裏用到了 Mongoose,須要先安裝 npm install mongoose -S 。安裝以後在項目中引入並鏈接到數據庫 userdb

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/userdb', {useMongoClient: true});

鏈接成功以後,定義一個 Schema,它一種以文件形式存儲的數據庫模型骨架,不具有數據庫的操做能力。

var userSchema = new mongoose.Schema({
    username: String,
    email: String
})

這裏的 userSchema 還不能對數據庫進行操做,只是定義了數據模型屬性 username, email 爲字符串類型。須要將該 Schema 發佈爲 Model,Model 是由 Schema 發佈生成的模型,具備抽象屬性和行爲的數據庫操做對。

var model = mongoose.model('user', userSchema);

最後 model 就能夠對數據庫進行操做了,把上面的代碼封裝成 userModel.js 到根目錄下新建一個 models/ 目錄下面,用 module.exports = model; 將 model 暴露出來供其餘文件使用。

在 user.js 路由文件裏,咱們來引入 userModel.js 進行數據庫操做。

var userModel = require('../models/userModel.js');

router.get('/list', function(req, res, next) {
  userModel.find(function(err, data){
    if(err){ return console.log(err) }
    res.render('UserList',{
      user: data
    })
  })
});

這裏使用 userModel.find() 查詢到全部用戶。可是如今數據庫裏仍是空的,咱們來新增一個添加用戶頁面向數據庫裏插入數據。

添加用戶

在 views/ 目錄下新建 UserAdd.html 添加用戶視圖

<!DOCTYPE html>
<html>
<head>
    <title>用戶編輯頁面</title>
</head>
<body>
    <form action="/users/add" method="post">
        <input type="text" name="username" value="">
        <input type="email" name="email" value="">
        <button type="submit">submit</button>
    </form>
</body>
</html>

在 user.js 路由文件裏來添加對應視圖的路由

router.get('/add', function(req, res, next) {
  res.render('UserAdd');
});

這是渲染視圖頁面的路由,咱們須要添加一個 post 方法的路由,在點擊提交按鈕的時候,把數據存進數據庫裏。

router.post('/add', function(req, res, next) {
  var newUser = new userModel({
    username: req.body.username,
    email: req.body.email
  })
  newUser.save(function(err, data){
    if(err){ return console.log(err) }
    res.redirect('/users/list');
  })
});

這裏使用 new userModel() 建立了一個 Entity,它是由 Model 建立的實體,它的操做也會影響數據庫。newUser 調用 save() 方法將數據保存到數據庫中。而後 res.redirect() 將頁面重定向到用戶列表頁面,這時就能夠看到咱們新增的用戶顯示在列表中了。接下來咱們看看如何來編輯用戶信息。

編輯用戶

依然是建立相應的用戶編輯視圖:UserEdit.html

<!DOCTYPE html>
<html>
<head>
    <title>用戶編輯頁面</title>
</head>
<body>
    <form action="/users/update" method="post">
        <input type="hidden" name="id" value="<%= user._id %>">
        <input type="text" name="username" value="<%= user.username %>">
        <input type="email" name="email" value="<%= user.email %>">
        <button type="submit">update</button>
    </form>
</body>
</html>

添加對應的路由:/users/edit/:id 來渲染視圖,/users/update 來修改數據庫數據

router.get('/edit/:id', function (req, res, next) {
  var id = req.params.id;
  userModel.findOne({_id: id}, function (err, data) {
    res.render('UserEdit', {
      user: data
    })
  })
});
router.post('/update', function (req, res, next) {
  var id = req.body.id;
  userModel.findById(id, function (err, data) {
    if(err){ return console.log(err); }
    data.username = req.body.username;
    data.email = req.body.email;
    data.save(function(err){
      res.redirect('/users/list');
    })
  })
});

userModel.findOne() 會根據查詢條件 {_id: id} 查詢到對應的一條數據,那麼同理,查看用戶詳情的實現也是如此,只是渲染你到另一個模板而已,這裏就不重複寫了;userModel.findById() 查詢到 data 對象,該對象也屬於 Entity,有 save() 操做。req.body.username 就能夠獲取到咱們修改後的 username,修改 data 對象以後調用 save() 方法保存到數據庫中。接下來看看如何刪除用戶吧。

刪除用戶

在用戶列表中,點擊刪除按鈕,就把該用戶從數據庫中給刪除了,不須要視圖,那直接寫路由吧。

router.delete('/del', function (req, res) {
  var id = req.query.id;
  userModel.remove({_id: id}, function (err, data) {
    if(err){ return console.log(err); }
    res.json({code: 200, msg: '刪除成功'});
  })
})

點擊按鈕,發送刪除的請求,那咱們可使用 ajax 來實現。在用戶列表頁面引入 jquery,方便咱們操做。而後添加 ajax 請求

$('.del').on('click',function(){
    var id = $(this).data('id');
    $.ajax({
        url: '/users/del?id='+id,
        type: 'delete',
        success: function (res) { console.log(res); }
    })
})

重啓服務器,進入 users/list,點擊刪除按鈕,若是看到控制檯中已經打印了 {code: 200, msg: '刪除成功'} ,表示已經成功刪除了,這時咱們刷新頁面,看看列表中確實已經不存在該用戶了。

代碼地址: express-demo

總結

經過對用戶的增刪查改,學習如何寫路由已經如何操做數據庫。咱們來總結一下:

  1. 定義 Schema,由 Schema 發佈 Model 來操做數據庫。
  2. Model 建立的實體 Entity,能夠調用 save() 方法將數據保存到數據庫中。
  3. Model.find() 方法查詢到該 Schema 下的全部數據,findOne() 根據條件查詢數據,findById() 根據 id 查詢數據。
  4. Model.remove() 刪除數據。

更多文章:lin-xin/blog

相關文章
相關標籤/搜索