好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

express+mongoose实现对mongodb增删改查操作详解

本文实例讲述了 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"改为下面的写法

?

1

2

3

"scripts" : {

  "start" : "supervisor ./bin/www"

  },

以后要启动项目只需要在项目文件夹下,执行 npm start 即可。

改写文件

 

由于express自己生成的文件结构不那么优美,所以稍微修改一下,方便接下来的工作。
首先打开 \route 文件夹,删除没用的 user.js ,打开 index.js ,修改为下面的内容:

?

1

2

3

4

5

6

'use strict'

const routes = (app) => {

  app.get( '/' , (req, res, next) => {

   res.render( 'index' , { title: 'Jrain真的很帅' })

  })

}

然后打开 app.js 文件夹,修改为以下内容:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

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,接下来就到真正的开发啦!

增删改查功能实现

 

在根目录下,新建一个 modules 文件夹,里面新建一个叫做 my_class.js 的文件。我们这个项目是建立一个班级学生管理系统,能够对学生的姓名及学号进行增删改查的操作。文件内容如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

'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

然后我们回到 \routes\index.js ,我们几乎所有的逻辑都会在这里面进行。

把当中内容修改为下面的代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

'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() ,作为删除学生信息用。

我们的项目已经全部完成了,测试一下吧!

尾声

 

这篇东西不是教程,仅作为自己学习的一个记录。如果能够对他人有用就最好啦,如果觉得我哪里说得不对也欢迎指正。谢谢大家~!

希望本文所述对大家MongoDB数据库程序设计有所帮助。

原文链接:https://segmentfault.com/a/1190000004873740

查看更多关于express+mongoose实现对mongodb增删改查操作详解的详细内容...

  阅读:24次