帮助中心/最新通知

质量为本、客户为根、勇于拼搏、务实创新

< 返回文章列表

【服务器相关】教你如何通过express+mongoose实现对mongodb增删改查操作

发表时间:2025-06-16 03:46:00 小编:主机乐-Yutio

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

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 = resclassModel.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='http://www.hanyinnetwork.com/'>添加成功,点击返回首页</a>")}) }) // 删除学生信息 app.get('/del', (req, res, next) => {let response = resclassModel.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='http://www.hanyinnetwork.com/'>删除成功,点击返回首页</a>")}) }) // 修改学生信息 app.get('/update', (req, res, next) => {let response = resclassModel.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='http://www.hanyinnetwork.com/'>修改成功,点击返回首页</a>")}) }) // 查找学生 app.get('/reach', (req, res, next) => {let result = nullres.render('reach', { result }) }) app.post('/reach', (req, res, next) => {console.log(req.body)let response = reslet reachType = req.body.reach_type, keyWord = req.body.keywordif (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数据库程序设计有所帮助。


联系我们
返回顶部