建立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')