香港云主机最佳企业级服务商!

ADSL拨号VPS包含了中国大陆(联通,移动,电信,)

中国香港,国外拨号VPS。

当前位置:云主机 > Mongodb >

电信ADSL拨号VPS
联通ADSL拨号VPS
移动ADSL拨号VPS

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


时间:2020-11-14 13:39 作者:admin


本文实例讲述了express+mongoose实现对mongodb增删改查操作。分享给大家供大家参考,具体如下:

项目地址:https://github.com/jrainlau/mongoose_crud


写在开头

本文主要分享我如何使用express+mongoose对mongodb实现增删改查操作,感谢cnode社区所有精品文章的帮助,以及@airuikun的开源项目airuikun/mongoose_crud对我的启发。
学习nodejs已经小半个月了,一直琢磨着做一些什么东西出来。由于有着一定的PHP经验,所以对数据库的操作比较感兴趣。乘着学习nodejs的势头,就打算把mongodb也一并学了。mongodb给我的感觉会比mysql/' target='_blank'>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 setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'ejs');// uncomment after placing your favicon in /publicapp.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 handlerapp.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err);});// error handlers// development error handler// will print stacktraceif (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 userapp.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')// 连接mongodbmongoose.connect('mongodb://localhost/test')// 实例化连接对象const db = mongoose.connectiondb.on('error', console.error.bind(console, '连接错误:'))db.once('open', (callback) => { console.log('MongoDB连接成功!!')})// 创建schemaconst classSchema = new mongoose.Schema({ name: String, studentId: Number})// 创建modelconst 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(),作为删除学生信息用。

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

尾声

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

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

(责任编辑:admin)






帮助中心
会员注册
找回密码
新闻中心
快捷通道
域名登录面板
虚机登录面板
云主机登录面板
关于我们
关于我们
联系我们
联系方式

售前咨询:17830004266(重庆移动)

企业QQ:383546523

《中华人民共和国工业和信息化部》 编号:ICP备00012341号

Copyright © 2002 -2018 香港云主机 版权所有
声明:香港云主机品牌标志、品牌吉祥物均已注册商标,版权所有,窃用必究

云官方微信

在线客服

  • 企业QQ: 点击这里给我发消息
  • 技术支持:383546523

  • 公司总台电话:17830004266(重庆移动)
  • 售前咨询热线:17830004266(重庆移动)