cate 表
const mongoose = require('mongoose');
const { Schema, model } = mongoose;
const CateSchema = new Schema({
// 标题
title: { type: String, required: true },
}, { timestamps: true });
module.exports = model('cate', CateSchema);
food表
const mongoose = require('mongoose');
const { Schema, model } = mongoose;
const FoodSchema = new Schema({
// 标题
title: { type: String, required: true },
// 分类
cate_id: {
type: Schema.Types.ObjectId,
ref: 'cate', // cate 表 的model name
},
}, { timestamps: true });
module.exports = model('food', FoodSchema);
- 在 food 的控制层 内 执行查询操作
populate 的是关联表之间的查询 , 通过food表中的cate_id 和 cate表的_id相互关联
populate 的第一个参数是表关联之间的纽带,第二个参数表示过滤参数即是否返回当前参数,1 表示返回, 0 表示不反悔。
populate可以写多个串联,populate(‘cate_id’).populate(‘test_id’)…populate(‘demo_id’)… 需要在foo的表中先建立关系
// 详情
async findOne(ctx) {
const { id: _id } = ctx.query
const detail = await Food.find({ _id }).populate('cate_id', { title: 1, _id: 1 })
}