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 })
}