基于nodejs、mongodb之外卖平台后端接口开发文档(四)
2021-06-25 本文已影响0人
风中凌乱的男子
前言: 这一章我们来实现这个模块的增删改查接口

- 首先来设计接口模型,在modes文件夹下新建Category.js,模型结构如下:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const categorySchema = new Schema({
// 上级id,默认0是顶级分类
pid: { type: String, required: true, default: 0 },
// 分类名称
categoryName: { type: String, required: true },
// 分类图片
coverUrl: { type: String, required: true },
// 是否是外链,默认不是外链
isLinks: { type: String, required: true, default: "no" },
// 外链地址
links: { type: String },
// 是否在首页显示,默认不显示
isShowHome: { type: String, required: true, default: "no" },
date: { type: Date, default: Date.now }
})
module.exports = Category = mongoose.model("Category", categorySchema)
- 然后在routers文件夹下新建category.js,引入基础代码,在app.js也要引入
ps:后面就不在一一说明引入的事情了,总之要记得 ,新建的路由js和模型js一定要在app.js内引入才生效
var express = require('express');
var router = express.Router();
//引入模型
var Category = require("../models/Category");
//引入过滤filter.js
const filter = require("../utils/filter")
//引入token.js
var vertoken = require('../utils/token')
/** 接口区域 */
/** 接口区域 */
module.exports = router;
- 下面开发新增分类接口
//新增分类接口
router.post('/category/add', filter.categoryAddFilter, (req, res) => {
const categorys = {}
if (req.body.pid) categorys.pid = req.body.pid;
if (req.body.categoryName) categorys.categoryName = req.body.categoryName;
if (req.body.coverUrl) categorys.coverUrl = req.body.coverUrl;
if (req.body.isLinks) categorys.isLinks = req.body.isLinks;
if (req.body.links) categorys.links = req.body.links;
if (req.body.isShowHome) categorys.isShowHome = req.body.isShowHome;
new Category(categorys).save().then((val) => {
res.json({
code: 200,
message: '新增成功'
});
})
})
- 下面开发查询分类接口
//查询分类列表,默认查询顶级的显示在首页的分类
router.post('/category/list', (req, res) => {
Category.find({ pid: '0', isShowHome: 'yes' }, (err, docs) => {
if (docs.length == 0) {
res.json({
code: -1,
message: "暂无数据"
})
} else {
res.json({
code: 200,
data: docs,
message: '查询成功'
})
}
})
})
- 下面开发修改分类的接口,这里加了校验token是否过期的逻辑
//修改分类接口
router.put('/category/update/:id', (req, res) => {
vertoken.getToken(req.headers.token).then((data) => {
const categorys = {}
if (req.body.pid) categorys.pid = req.body.pid;
if (req.body.categoryName) categorys.categoryName = req.body.categoryName;
if (req.body.coverUrl) categorys.coverUrl = req.body.coverUrl;
if (req.body.isLinks) categorys.isLinks = req.body.isLinks;
if (req.body.links) categorys.links = req.body.links;
if (req.body.isShowHome) categorys.isShowHome = req.body.isShowHome;
Category.findOneAndUpdate({ _id: req.params.id }, { $set: categorys }, {
new: true
}).then(docs => res.json({
code: 200,
message: "修改成功"
}))
}).catch(err => {
res.json({
code: 401,
message: "token失效了"
})
})
})
- 下面开发删除分类的接口
//删除分类接口
router.delete('/category/delete/:id', (req, res) => {
Category.findOneAndRemove({ _id: req.params.id }).then(docs => {
res.json({
code: 200,
message: "删除成功"
})
}).catch(err => {
res.json({
code: -1,
data: err,
message: "删除失败"
})
});
})
end
接下一章