var productSchema = Schema({
product_code: String,
name: {
type: String,
required: true
},
description: String,
category:{
type: String,
ref: 'Product_Category'
},
umo: String,
threshold: {
type:Number,
default: 0
},
image: String,
isactive: {
type: Boolean,
default: true
}
});
var product_categorySchema = Schema({
isactive: {
type: Boolean,
default: true
},
name: {
type: String,
required: true
},
description: String
});
我从类别中删除了这两个模式,但如果我在产品表中有与该类别相对应的数据,则不应删除该类别。有人可以帮忙吗?
它应该看起来像这样:
// Function which delete the category behind the given _id
async function deleteCategory(idCategory) {
// check if there is a product related to the category
const ret = await product_schema.findOne({
category: idCategory,
});
// if there is, return an error
if (ret) throw new Error('Cannot delete the category');
// else do delete the category
return product_category_schema.remove({
_id: idCategory,
});
}
你还必须知道:
category:{
type: String,
ref: 'Product_Category'
},
不是设置参考的正确方法;它应该是一个ObjectId
而不是String
const {
Schema,
} = mongoose;
category:{
type: Schema.Types.ObjectId,
ref: 'Product_Category'
},
首先,请在产品架构中更新“类别”字段的“类型”属性,如下所示:
category:{
type: Schema.Types.ObjectId,
ref: 'Category' // model name
}`
并声明这样的模型:
var Product = mongoose.model('Product', productSchema );
然后使用“distinct”查询和“$ nin”查询运算符来删除产品架构未引用的类别,如下所示:
Product.find().distinct('category').then((data)=>{
Category.deleteMany({_id: {$nin: data}}).then(del => {
console.log("deleted",del)
})
})