最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

express+mongoose實(shí)現(xiàn)對mongodb增刪改查操作詳解

 更新時(shí)間:2020年05月11日 10:20:54   作者:jrainlau  
這篇文章主要介紹了express+mongoose實(shí)現(xiàn)對mongodb增刪改查操作,結(jié)合實(shí)例形式分析了express+mongoose對mongodb增刪改查操作基本實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了express+mongoose實(shí)現(xiàn)對mongodb增刪改查操作。分享給大家供大家參考,具體如下:

項(xiàng)目地址:https://github.com/jrainlau/mongoose_crud


寫在開頭

本文主要分享我如何使用express+mongoose對mongodb實(shí)現(xiàn)增刪改查操作,感謝cnode社區(qū)所有精品文章的幫助,以及@airuikun的開源項(xiàng)目airuikun/mongoose_crud對我的啟發(fā)。
學(xué)習(xí)nodejs已經(jīng)小半個(gè)月了,一直琢磨著做一些什么東西出來。由于有著一定的PHP經(jīng)驗(yàn),所以對數(shù)據(jù)庫的操作比較感興趣。乘著學(xué)習(xí)nodejs的勢頭,就打算把mongodb也一并學(xué)了。mongodb給我的感覺會(huì)比MySQL靈活一點(diǎn),也比較好上手。掌握了一定的mongodb知識(shí)以后,便開始著手開發(fā),實(shí)現(xiàn)最基礎(chǔ)的增刪改查功能。


項(xiàng)目準(zhǔn)備

首先你需要掌握一定的nodejs,express以及mongodb的知識(shí),并且已經(jīng)安裝好express和mongoose模塊,同時(shí)電腦安裝有mongodb。關(guān)于mongodb的問題,可以移步我的另一篇文章:win7下快速啟動(dòng)mongodb的方法,里面有詳細(xì)的安裝及配置過程。同時(shí)推薦使用robomongo作為mongodb的可視化操作工具,方便我們直接查看和操作數(shù)據(jù)庫。

項(xiàng)目開始

打開命令行,輸入
express -e mongoose_crud
“-e”表示使用ejs作為模版引擎(jade太丑不喜歡)。生成項(xiàng)目文件結(jié)構(gòu)以后,執(zhí)行
cd mongoose_crud && npm install安裝依賴包。
現(xiàn)在我們的項(xiàng)目應(yīng)該長這樣的(modules文件夾是我自己建的,后面會(huì)講到):


為了方便接下來的操作,推薦使用supervisor來啟動(dòng)項(xiàng)目
npm install supervisor -g
進(jìn)入我們的項(xiàng)目文件夾,我們改寫一下package.json文件,把里面的"scripts"改為下面的寫法

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

以后要啟動(dòng)項(xiàng)目只需要在項(xiàng)目文件夾下,執(zhí)行npm start即可。

改寫文件

由于express自己生成的文件結(jié)構(gòu)不那么優(yōu)美,所以稍微修改一下,方便接下來的工作。
首先打開\route文件夾,刪除沒用的user.js,打開index.js,修改為下面的內(nèi)容:

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

然后打開app.js文件夾,修改為以下內(nèi)容:

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;

其實(shí)就是把路由管理從app.js遷移到了\routes\index.js,方便我們管理。

我們可以測試一下,在瀏覽器輸入localhost:3000,如果輸出不是“Jrain真的很帥”,那就是你的項(xiàng)目出了問題。OK,接下來就到真正的開發(fā)啦!

增刪改查功能實(shí)現(xiàn)

在根目錄下,新建一個(gè)modules文件夾,里面新建一個(gè)叫做my_class.js的文件。我們這個(gè)項(xiàng)目是建立一個(gè)班級(jí)學(xué)生管理系統(tǒng),能夠?qū)W(xué)生的姓名及學(xué)號(hào)進(jìn)行增刪改查的操作。文件內(nèi)容如下:

'use strict'
const mongoose = require('mongoose')
// 連接mongodb
mongoose.connect('mongodb://localhost/test')
// 實(shí)例化連接對象
const db = mongoose.connection
db.on('error', console.error.bind(console, '連接錯(cuò)誤:'))
db.once('open', (callback) => {
 console.log('MongoDB連接成功?。?)
})
// 創(chuàng)建schema
const classSchema = new mongoose.Schema({
 name: String,
 studentId: Number
})
// 創(chuàng)建model
const classModel = mongoose.model('newClass', classSchema) // newClass為創(chuàng)建或選中的集合

module.exports = classModel

每一段的作用看注釋即可?,F(xiàn)在我們已經(jīng)把項(xiàng)目跟mongodb連接好了,可以進(jìn)行接下來的步驟。

我們會(huì)有5個(gè)頁面,分別是首頁,學(xué)生信息增加頁面,學(xué)生刪除頁面,學(xué)生修改頁面,學(xué)生查找頁面。在\views文件夾內(nèi)建立相應(yīng)的ejs文件即可,代碼就不貼了,可以直接到項(xiàng)目去看:
https://github.com/jrainlau/mongoose_crud/tree/master/views

然后我們回到\routes\index.js,我們幾乎所有的邏輯都會(huì)在這里面進(jìn)行。

把當(dāng)中內(nèi)容修改為下面的代碼:

'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 })
  })
 })
 // 增加學(xué)生信息
 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='/'>添加成功,點(diǎn)擊返回首頁</a>")
  })
 })
 // 刪除學(xué)生信息
 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='/'>刪除成功,點(diǎn)擊返回首頁</a>")
  })
 })
 // 修改學(xué)生信息
 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("請勾選待修改的學(xué)生")</script>')
   }
   res.send("<a href='/'>修改成功,點(diǎn)擊返回首頁</a>")
  })
 })
 // 查找學(xué)生
 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請求接收參數(shù),進(jìn)行相應(yīng)的操作,實(shí)現(xiàn)增刪改查的功能。主要用到的API有如下幾個(gè):

  • .find(),作為讀取、查找學(xué)生信息用。

  • .create(),作為增加學(xué)生信息用。它是基于mongoose中的model的操作,傳入一個(gè)json對象作為需要添加的內(nèi)容,具體可自行查閱。

  • .update(),作為更新學(xué)生信息用。

  • .remove(),作為刪除學(xué)生信息用。

我們的項(xiàng)目已經(jīng)全部完成了,測試一下吧!

尾聲

這篇東西不是教程,僅作為自己學(xué)習(xí)的一個(gè)記錄。如果能夠?qū)λ擞杏镁妥詈美玻绻X得我哪里說得不對也歡迎指正。謝謝大家~!

希望本文所述對大家MongoDB數(shù)據(jù)庫程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • MongoDB復(fù)制集原理詳解

    MongoDB復(fù)制集原理詳解

    這篇文章主要介紹了MongoDB復(fù)制集原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • MongoDB 3.6版本中bind_ip設(shè)置詳解

    MongoDB 3.6版本中bind_ip設(shè)置詳解

    這篇文章主要給大家介紹了關(guān)于MongoDB 3.6版本中bind_ip設(shè)置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • Laravel?框架中使用?MongoDB?數(shù)據(jù)庫的操作

    Laravel?框架中使用?MongoDB?數(shù)據(jù)庫的操作

    這篇文章主要介紹了Laravel?框架中使用?MongoDB?數(shù)據(jù)庫的問題及操作方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-03-03
  • MongoDB安全配置詳解

    MongoDB安全配置詳解

    這篇文章主要介紹了MongoDB安全配置詳解,本文來自國內(nèi)安全廠商烏云平臺(tái),講解的還是比較全面的,需要的朋友可以參考下
    2015-05-05
  • MongoDB中sort()排序方法、aggregate()聚合方法和索引代碼示例

    MongoDB中sort()排序方法、aggregate()聚合方法和索引代碼示例

    這篇文章主要給大家介紹了關(guān)于MongoDB中sort()排序方法、aggregate()聚合方法和索引的相關(guān)資料,MongoDB的聚合函數(shù)Aggregate是一組用于對MongoDB中的數(shù)據(jù)集進(jìn)行聚合操作的函數(shù),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • MongoDB數(shù)據(jù)庫常用28條查詢語句總結(jié)

    MongoDB數(shù)據(jù)庫常用28條查詢語句總結(jié)

    我們經(jīng)常使用的MySQL是最流行的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),隨著時(shí)代的進(jìn)步,互聯(lián)網(wǎng)的發(fā)展關(guān)系型數(shù)據(jù)庫已經(jīng)不滿足于互聯(lián)網(wǎng)的需求,因此出現(xiàn)了非關(guān)系數(shù)據(jù)庫,下面這篇文章主要給大家總結(jié)介紹了關(guān)于MongoDB數(shù)據(jù)庫常用28條查詢語句,需要的朋友可以參考下
    2023-05-05
  • Centos7 yum安裝mongodb實(shí)現(xiàn)步驟詳解

    Centos7 yum安裝mongodb實(shí)現(xiàn)步驟詳解

    這篇文章主要介紹了Centos7 yum安裝mongodb實(shí)現(xiàn)步驟詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • MongoDB中的bson介紹和使用實(shí)例

    MongoDB中的bson介紹和使用實(shí)例

    這篇文章主要介紹了MongoDB中的bson介紹和使用實(shí)例,本文講解了什么是bson、bson在MongoDB中的使用、幾個(gè)BSON的例子等內(nèi)容,需要的朋友可以參考下
    2015-05-05
  • MongoDB數(shù)據(jù)庫的特色和優(yōu)點(diǎn)介紹

    MongoDB數(shù)據(jù)庫的特色和優(yōu)點(diǎn)介紹

    這篇文章主要介紹了MongoDB數(shù)據(jù)庫的特色和優(yōu)點(diǎn)介紹,本文總結(jié)了每個(gè)開發(fā)人員都應(yīng)該知道的5個(gè)MongoDB特點(diǎn),需要的朋友可以參考下
    2015-05-05
  • MongoDB中的Primary Shard詳解

    MongoDB中的Primary Shard詳解

    在MongoDB的Sharding架構(gòu)中,每個(gè)database中都可以存儲(chǔ)兩種類型的集合,一種是未分片的集合,一種是通過分片鍵,被打散的集合,下面給大家介紹MongoDB中的Primary Shard詳解,感興趣的朋友跟隨小編一起看看吧
    2024-08-08

最新評論

铁岭县| 高唐县| 克拉玛依市| 邹平县| 正镶白旗| 涿鹿县| 朝阳县| 永修县| 阳春市| 建瓯市| 平谷区| 永嘉县| 万州区| 紫阳县| 汶上县| 梅河口市| 温宿县| 昭平县| 濮阳县| 昆明市| 三河市| 旬邑县| 石城县| 兰溪市| 黑山县| 神池县| 开鲁县| 沛县| 安新县| 东丽区| 辽宁省| 奎屯市| 嘉峪关市| 元氏县| 合作市| 南乐县| 南康市| 民乐县| 祁阳县| 阿城市| 阿拉善盟|