我正在使用 nodejs 创建一个电子商务网站。理想情况下,产品将具有类别和子类别。但是我正在创建的内容应该与任何类型的电子商务网站一起使用,因此,可能不需要子类别字段。
在产品模式中,我添加了与子类别文档相关的子类别字段。并且子类别文档与类别文档相关。
我的问题是,没有子类别的产品如何添加到数据库中?
类别架构:
const categorySchema = mongoose.Schema({
name: {
type: String,
required: true,
}
})
module.exports = mongoose.model('Category', categorySchema);
子类别架构:
const subCategorySchema = mongoose.Schema({
name: {
type: String,
required: true,
},
Category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
required:true
},
})
module.exports = mongoose.model('SubCategory', subCategorySchema);
产品架构:
const productSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true
},
price : {
type: Number,
default:0
},
SubCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: 'SubCategory',
required:true
},
countInStock: {
type: Number,
required: true,
min: 0,
max: 255
},
})
module.exports = mongoose.model('Product', productSchema);
提前致谢...
恐怕您的 ProductSchema 中必须有一个必填的 Category 字段和一个不需要的 SubCategory 字段。这样,您将确保您的所有产品至少有一个类别,并允许添加一个子类别:
const productSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true
},
price : {
type: Number,
default:0
},
Category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
required: true
},
SubCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: 'SubCategory',
required: false
},
countInStock: {
type: Number,
required: true,
min: 0,
max: 255
},
})
如果你想确保类别和子类别的层次结构,你总是可以在你的预保存中添加一些中间件验证:
productSchema.pre('save', async function (next) {
if (this.SubCategory) {
try {
const check = await SubCategory.findById(this.SubCategory);
if (!check || JSON.stringify(check.Category) !== JSON.stringify(this.Category)) {
throw new Error('Check your Category and/or SubCategory');
}
} catch (error) {
throw error;
}
}
next();
});
为了更简单,你应该创建嵌套类别,就像
型号
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
parentId: {
type: String,
},
},
{ timestamps: true }
);
以及获取类别及其子类别
const categories = await Category.find({});
const categoryList = createCategories(categories);
res.status(201).json({
success: true,
categoryList,
});
const createCategories = (categories, parentId = null) => {
const categoryList = [];
let category;
if (parentId == undefined) {
category = categories.filter((cat) => cat.parentId == undefined);
} else {
category = categories.filter((cat) => cat.parentId == parentId);
}
for (let cate of category) {
categoryList.push({
_id: cate._id,
name: cate.name,
children: createCategories(categories, cate._id),
});
}
return categoryList;
};
我有类似的问题:
我有一个表格,但不确定如何同时更新产品类别和子类别。 ejs 表单应显示一个带有可用类别和子类别的选择下拉菜单。当我点击保存时,新选择的类别被更新。意味着产品被移到不同的类别?有什么想法吗?
Url 路由是 /product/edit/:id