歡迎您光臨本站 註冊首頁

express+mongoose實現對mongodb增刪改查操作詳解

←手機掃碼閱讀     sl_ivan @ 2020-05-12 , reply:0

本文例項講述了express+mongoose實現對mongodb增刪改查操作。分享給大家供大家參考,具體如下:
專案地址:https://github.com/jrainlau/mongoose_crud
寫在開頭
本文主要分享我如何使用express+mongoose對mongodb實現增刪改查操作,感謝cnode社群所有精品文章的幫助,以及@airuikun的開源專案airuikun/mongoose_crud對我的啟發。
學習nodejs已經小半個月了,一直琢磨著做一些什麼東西出來。由於有著一定的PHP經驗,所以對資料庫的操作比較感興趣。乘著學習nodejs的勢頭,就打算把mongodb也一併學了。mongodb給我的感覺會比MySQL靈活一點,也比較好上手。掌握了一定的mongodb知識以後,便開始著手開發,實現最基礎的增刪改查功能。
專案準備
首先你需要掌握一定的nodejs,express以及mongodb的知識,並且已經安裝好express和mongoose模組,同時電腦安裝有mongodb。關於mongodb的問題,可以移步我的另一篇文章:win7下快速啟動mongodb的方法,裡面有詳細的安裝及配置過程。同時推薦使用robomongo作為mongodb的視覺化操作工具,方便我們直接檢視和運算元據庫。
專案開始
開啟命令列,輸入
express -e mongoose_crud
「-e」表示使用ejs作為模版引擎(jade太醜不喜歡)。生成專案檔案結構以後,執行
cd mongoose_crud && npm install 安裝依賴包。
現在我們的專案應該長這樣的(modules資料夾是我自己建的,後面會講到):
為了方便接下來的操作,推薦使用 supervisor 來啟動專案
npm install supervisor -g
進入我們的專案資料夾,我們改寫一下 package.json 檔案,把裡面的"scripts"改為下面的寫法
"scripts": { "start": "supervisor ./bin/www" },
以後要啟動專案只需要在專案資料夾下,執行 npm start 即可。
改寫檔案
由於express自己生成的檔案結構不那麼優美,所以稍微修改一下,方便接下來的工作。
首先開啟   oute 資料夾,刪除沒用的 user.js ,開啟 index.js ,修改為下面的內容:
'use strict' const routes = (app) => { app.get('/', (req, res, next) => { res.render('index', { title: 'Jrain真的很帥'}) }) }
然後開啟 app.js 資料夾,修改為以下內容:
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 遷移到了   outesindex.js ,方便我們管理。
我們可以測試一下,在瀏覽器輸入 localhost:3000 ,如果輸出不是「Jrain真的很帥」,那就是你的專案出了問題。OK,接下來就到真正的開發啦!
增刪改查功能實現
在根目錄下,新建一個 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_crud/tree/master/views
然後我們回到   outesindex.js ,我們幾乎所有的邏輯都會在這裡面進行。
把當中內容修改為下面的程式碼:
'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("新增成功,點選返回首頁") }) }) // 刪除學生資訊 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("刪除成功,點選返回首頁") }) }) // 修改學生資訊 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('

') } res.send("修改成功,點選返回首頁") }) }) // 查詢學生 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() ,作為刪除學生資訊用。
我們的專案已經全部完成了,測試一下吧!


[sl_ivan ] express+mongoose實現對mongodb增刪改查操作詳解已經有278次圍觀

http://coctec.com/docs/service/show-post-234080.html