加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 服务器 > 系统 > 正文

express+mongoose实现对mongodb增删改查

发布时间:2023-11-10 16:39:23 所属栏目:系统 来源:
导读:  学习nodejs已经小半个月了,一直琢磨着做一些什么东西出来。由于有着一定的PHP经验,所以对数据库的操作比较感兴趣。乘着学习nodejs的势头,就打算把mongodb也一并学了。mongodb给我的感觉会比MySQL灵活一点,也
  学习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文件夹是我自己建的,后面会讲到):
 
  express+mongoose如何实现对mongodb增删改查
 
  为了方便接下来的操作,推荐使用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有如下几个:
 
  .find(),作为读取、查找学生信息用。
 
  .create(),作为增加学生信息用。它是基于mongoose中的model的操作,传入一个json对象作为需要添加的内容,具体可自行查阅。
 
  .update(),作为更新学生信息用。
 
  .remove(),作为删除学生信息用。
 
  我们的项目已经全部完成了,测试一下吧!
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章