全栈课程笔记:通用CRUD接口以及mongodb模型创建
建立mongodb模型
一、安装必要模块
npm i inflection -s
inflection 是用来将字符串转换为类名的模块,在本项目中会很便捷的对接CRUD通用接口的路由操作。
二、创建模型
首先我们依次建立 models/Category.js models/Item.js
const mongoose = require('mongoose')
const schema = new mongoose.Schema({
name: { type: String },
parent: { type: mongoose.SchemaTypes.ObjectId, ref: 'Category' }
})
module.exports = mongoose.model('Category', schema)
type: mongoose.SchemaTypes.ObjectId 是表示类型为mongodb中的ID号特殊类型
ref: 'Category' 表示关联对应关系
三、CRUD通用接口
module.exports = app => {
const express = require('express')
const router = express.Router()
const Category = require('../../models/Category')
const Item = require('../../models/Item')
router.post('/', async (req, res) => {
const model = await req.Model.create(req.body)
res.send(model)
})
router.put('/:id', async (req, res) => {
const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
res.send(model)
})
router.delete('/:id', async (req, res) => {
const model = await req.Model.findByIdAndDelete(req.params.id)
res.send({
'success': true
})
})
router.get('/', async (req, res) => {
const queryOptions = {}
if (req.Model.modelName == 'Category') {
queryOptions.populate = 'parent'
}
const model = await req.Model.find().setOptions(queryOptions).limit(10)
res.send(model)
})
router.get('/:id', async (req, res) => {
const model = await req.Model.findById(req.params.id)
res.send(model)
})
app.use('/admin/api/rest/:resource', async (req, res, next) => {
const modelName = require('inflection').classify(req.params.resource)
req.Model = require(`../../models/${modelName}`)
next()
}, router)
}
首先使用中间件将传输过来的modelName转换为类名与模型相对应。