使用express+mongoose對mongodb實現增刪改查操做

項目地址:https://github.com/jrainlau/mongoose_cru...node


寫在開頭

本文主要分享我如何使用express+mongoose對mongodb實現增刪改查操做,感謝cnode社區全部精品文章的幫助,以及@airuikun的開源項目airuikun/mongoose_crud對個人啓發。
學習nodejs已經小半個月了,一直琢磨着作一些什麼東西出來。因爲有着必定的PHP經驗,因此對數據庫的操做比較感興趣。乘着學習nodejs的勢頭,就打算把mongodb也一併學了。mongodb給個人感受會比MySQL靈活一點,也比較好上手。掌握了必定的mongodb知識之後,便開始着手開發,實現最基礎的增刪改查功能。git


項目準備

首先你須要掌握必定的nodejs,express以及mongodb的知識,而且已經安裝好express和mongoose模塊,同時電腦安裝有mongodb。關於mongodb的問題,能夠移步個人另外一篇文章:win7下快速啓動mongodb的方法,裏面有詳細的安裝及配置過程。同時推薦使用robomongo做爲mongodb的可視化操做工具,方便咱們直接查看和操做數據庫。github

項目開始

打開命令行,輸入
express -e mongoose_crud
「-e」表示使用ejs做爲模版引擎(jade太醜不喜歡)。生成項目文件結構之後,執行
cd mongoose_crud && npm install安裝依賴包。
如今咱們的項目應該長這樣的(modules文件夾是我本身建的,後面會講到):
圖片描述
爲了方便接下來的操做,推薦使用supervisor來啓動項目
npm install supervisor -g
進入咱們的項目文件夾,咱們改寫一下package.json文件,把裏面的"scripts"改成下面的寫法mongodb

"scripts": {
    "start": "supervisor ./bin/www"
  },

之後要啓動項目只須要在項目文件夾下,執行npm start便可。數據庫

改寫文件

因爲express本身生成的文件結構不那麼優美,因此稍微修改一下,方便接下來的工做。
首先打開\route文件夾,刪除沒用的user.js,打開index.js,修改成下面的內容:express

'use strict'
const routes = (app) => {
    app.get('/', (req, res, next) => {
        res.render('index', { title: 'Jrain真的很帥'})
    })
}

而後打開app.js文件夾,修改成如下內容:npm

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');

var app = express();

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

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

routes(app)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

其實就是把路由管理從app.js遷移到了\routes\index.js,方便咱們管理。
咱們能夠測試一下,在瀏覽器輸入localhost:3000,若是輸出不是「Jrain真的很帥」,那就是你的項目出了問題。OK,接下來就到真正的開發啦!json

增刪改查功能實現

在根目錄下,新建一個modules文件夾,裏面新建一個叫作my_class.js的文件。咱們這個項目是創建一個班級學生管理系統,可以對學生的姓名及學號進行增刪改查的操做。文件內容以下:瀏覽器

'use strict'
const mongoose = require('mongoose')
// 鏈接mongodb
mongoose.connect('mongodb://localhost/test')
// 實例化鏈接對象
const db = mongoose.connection
db.on('error', console.error.bind(console, '鏈接錯誤:'))
db.once('open', (callback) => {
  console.log('MongoDB鏈接成功!!')
})
// 建立schema
const classSchema = new mongoose.Schema({
    name: String,
    studentId: Number
})
// 建立model
const classModel = mongoose.model('newClass', classSchema) // newClass爲建立或選中的集合

module.exports = classModel

每一段的做用看註釋便可。如今咱們已經把項目跟mongodb鏈接好了,能夠進行接下來的步驟。
咱們會有5個頁面,分別是首頁,學生信息增長頁面,學生刪除頁面,學生修改頁面,學生查找頁面。在\views文件夾內創建相應的ejs文件便可,代碼就不貼了,能夠直接到項目去看:
https://github.com/jrainlau/mongoose_cru...
而後咱們回到\routes\index.js,咱們幾乎全部的邏輯都會在這裏面進行。
把當中內容修改成下面的代碼:cookie

'use strict'
const classModel = require('../modules/my_class')
const routes = (app) => {
    // 首頁
    app.get('/', (req, res, next) => {
        let response = res
        classModel.find({}, (err, result, res) => {
            if(err) return console.log(err)
            response.render('index', { result })
        })
    })
    // 增長學生信息
    app.get('/create', (req, res, next) => {
        res.render('create', {})
    })
    app.post('/create', (req, res, next) => {
        let newStudent = [{
            name: req.body.name,
            studentId: req.body.student_id
        }]
        classModel.create(newStudent, (err) => {
            if(err) return console.log(err)
            res.send("<a href='/'>添加成功,點擊返回首頁</a>")
        })
    })
    // 刪除學生信息
    app.get('/del', (req, res, next) => {
        let response = res
        classModel.find({}, (err, result, res) => {
            if(err) return console.log(err)
            response.render('del', { result })
        })
    })
    app.post('/del', (req, res, next) => {
        classModel.remove({_id: req.body.student}, (err, result) => {
            if(err) return console.log(err)
            console.log(result.result)
            res.send("<a href='/'>刪除成功,點擊返回首頁</a>")
        })
    })
    // 修改學生信息
    app.get('/update', (req, res, next) => {
        let response = res
        classModel.find({}, (err, result, res) => {
            if(err) return console.log(err)
            response.render('update', { result })
        })
    })
    app.post('/update', (req, res, next) => {
        console.log(req.body)
        let num = req.body.num,
            condiction = {_id: req.body._id[num]},
            query = {$set: {name: req.body.name[num], studentId: req.body.student_id[num]}}
        classModel.update(condiction, query, (err, result) => {
            if(err) {
                console.log(err)
                res.send('<script>alert("請勾選待修改的學生")</script>')
            }
            res.send("<a href='/'>修改爲功,點擊返回首頁</a>")
        })
    })
    // 查找學生
    app.get('/reach', (req, res, next) => {
        let result = null
        res.render('reach', { result })
    })
    app.post('/reach', (req, res, next) => {
        console.log(req.body)
        let response = res
        let reachType = req.body.reach_type,
            keyWord = req.body.keyword
        if (reachType == 0) {
            classModel.find({name: keyWord}, (err, result) => {
                if(err) return console.log(err)
                response.render('reach', { result })
            })
        } else {
            classModel.find({studentId: keyWord}, (err, result) => {
                if(err) return console.log(err)
                response.render('reach', { result })
            })
        }
    })
}
module.exports = routes

其原理是,程序經過post請求接收參數,進行相應的操做,實現增刪改查的功能。主要用到的API有以下幾個:

  • .find(),做爲讀取、查找學生信息用。

  • .create(),做爲增長學生信息用。它是基於mongoose中的model的操做,傳入一個json對象做爲須要添加的內容,具體可自行查閱。

  • .update(),做爲更新學生信息用。

  • .remove(),做爲刪除學生信息用。

咱們的項目已經所有完成了,測試一下吧!
圖片描述

尾聲

這篇東西不是教程,僅做爲本身學習的一個記錄。若是可以對他人有用就最好啦,若是以爲我哪裏說得不對也歡迎指正。謝謝你們~!

相關文章
相關標籤/搜索