在后端开发中,增删查改是最常规的操作,而在用node框架express或koa开发后端时,经常搭配mongodb数据库,这篇文章就是教大家使用mongoose插件实现在node中对mongodb的增删查改操作
1.首先在相应路由中是引入相应的模型
const articleModel = require('../db/model/article')
我这里引入了一个文章模块,定义的Schema也比较简单,就title和content
2.增加文章路由接口
router.post('/add', (req, res) => {
const {title, content} = req.body //通过解构赋值获取前端传值
if (title && content) { // 判断是值是否都为真,否则走else返回参数错误
articleModel.create({title, content}, (err, data) => { // 使用Model.create执行新增操作
if (err) { // 如果函数回调报错,返回添加错误
res.send({
code: '111111',
msg: '添加错误'
})
} else { // 添加成功,返回添加成功
res.send({
code: '000000',
msg: '添加成功'
})
}
})
} else { //else返回参数错误
res.send({
code: '111111',
msg: '参数错误',
})
}
})
3.查询文章路由接口
router.get('/list', (req, res) => {
const {_id, title, content} = req.query // 解构赋值获取传参数据
const pageSize = Number(req.query.pageSize) || 5 // 获取pageSize(每页条数)传参,不传默认为5
const currentPage = Number(req.query.currentPage) || 1 // 获取currentPage(当前页)传参,不传默认为1
const findInfo = { // 查询参数信息设置,用过正则表达式实现模糊查询title和content
title: {$regex: new RegExp(title)},
content: {$regex: new RegExp(content)}
}
if (_id) { // 如果传参有_id,具体查询的_id,不传,则默认查全部
findInfo._id = _id
}
articleModel.find(findInfo)
.limit(pageSize) // 查询条数
.skip((currentPage - 1) * pageSize) // 跳过条数
.exec((err, data) => { // 用exec来拼接回调,实现复杂查询
articleModel.count((findInfo), (err2, count) => { // 查询成功的情况下,再查询下总条数
if (err || err2) { // 如果有错误就返回错误
res.send({
code: '111111',
msg: '查询错误'
})
} else { // 无报错的情况下,返回数据和每页条数,当前页及总条数
res.send({
code: '000000',
msg: '查询成功',
data: {
result: data,
pageSize,
currentPage,
total: count
}
})
}
})
})
})
4.修改文章路由接口
router.post('/update', (req, res) => {
const {_id, title, content} = req.body
const updateInfo = {}
if (title) {
updateInfo.title = title
}
if (content) {
updateInfo.content = content
}
if (_id && (title || content)) {
articleModel.updateOne({_id}, updateInfo, (err, data) => {
if (err) {
res.send({
code: '111112',
msg: '更新失败'
})
} else {
res.send({
code: '000000',
msg: '更新成功'
})
}
})
} else {
res.send({
code: '111111',
msg: '参数错误'
})
}
})
5.删除文章路由接口
router.post('/del', (req, res) => {
const {_id} = req.body
if (_id) {
articleModel.remove({_id}, (err, data) => {
if (err) {
res.send({
code: '111112',
msg: '删除失败'
})
} else {
res.send({
code: '000000',
msg: '删除成功'
})
}
})
} else {
res.send({
code: '111111',
msg: '参数错误'
})
}
})
到此,在node中使用mongoose对mongodb常规增删查改就已完成~