• 企业400电话
  • 网络优化推广
  • AI电话机器人
  • 呼叫中心
  • 全 部 栏 目

    网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    express+mongoose实现对mongodb增删改查操作详解
    POST TIME:2021-10-18 23:13

    本文实例讲述了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自己生成的文件结构不那么优美,所以稍微修改一下,方便接下来的工作。
    首先打开\route文件夹,删除没用的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迁移到了\routes\index.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

    然后我们回到\routes\index.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("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有如下几个:

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

    尾声

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

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

    您可能感兴趣的文章:
    • MongoDB实现基于关键词的文章检索功能(C#版)
    • 深入了解MongoDB 分布式集群
    • 开源 5 款超好用的数据库 GUI 带你玩转 MongoDB、Redis、SQL 数据库(推荐)
    • JAVA代码实现MongoDB动态条件之分页查询
    • MongoDB设计方法以及技巧示例详解
    • MongoDB数据库基础操作总结
    • win7平台快速安装、启动mongodb的方法
    • 使用Mongodb实现打卡签到系统的实例代码
    • 浅析MongoDB 全文检索
    上一篇:阿里云服务器部署mongodb的详细过程
    下一篇:CentOS7.2 安装 MongoDB 3.4的教程
  • 相关文章
  • 

    关于我们 | 付款方式 | 荣誉资质 | 业务提交 | 代理合作


    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    X

    截屏,微信识别二维码

    微信号:veteran88

    (点击微信号复制,添加好友)

     打开微信