【发布时间】:2021-06-30 12:23:42
【问题描述】:
我有两个模型的架构,一个是Category,另一个是subCategory。我们需要Category 来创建子类别模型,但Category 模型不必有subCategories。
这是我的subCategory 模型:
const Mongoose = require('mongoose');
const { Schema } = Mongoose;
// Brand Schema
const SubCategorySchema = new Schema({
name: {
type: String,
required:true
},
id: {
type: Schema.Types.String,
unique:true,
required:true
},
category: {
type: Schema.Types.ObjectId,
ref: 'Category',
required:true
},
updated: Date,
created: {
type: Date,
default: Date.now
}
});
module.exports = Mongoose.model('SubCategory', SubCategorySchema);
这是我的Category 模型:
const Mongoose = require('mongoose');
const { Schema } = Mongoose;
// Category Schema
const CategorySchema = new Schema({
name: {
type: String,
trim: true,
},
id: {
type: String,
required:true,
unique: true
},
image: {
type:String,
default:'http://res.cloudinary.com/wisecart/image/upload/v1616718691/kuy26lytx5k0lkvfkgrt.svg',
required:true
},
description: {
type: String,
trim: true
},
updated: Date,
created: {
type: Date,
default: Date.now
},
});
module.exports = Mongoose.model('Category', CategorySchema);
我正在使用 请求类别时如何填充子类别? 例如,我想得到一个响应
{
"image": "http://res.cloudinary.com/wisecart/image/upload/v1616718691/kuy26lytx5k0lkvfkgrt.svg",
"_id": "606605934b213d2887e3a840",
"name": "Samsung",
"description": "sama",
"id": "asa",
"subCategory": [{Subcategory with an Id of _id},{Subcategory with an Id of _id}],
"created": "2021-04-01T17:40:35.505Z",
"__v": 0
}
【问题讨论】:
-
是否要填充 SubCategorySchema 的类别字段?
-
是否要填充 SubCategorySchema 的类别字段?
标签: javascript node.js mongodb typescript mongoose