gpt4 book ai didi

javascript - 只删除那些在第一个表中没有对应第二个表的条目

转载 作者:行者123 更新时间:2023-11-30 14:22:38 25 4
gpt4 key购买 nike

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'
},

关于javascript - 只删除那些在第一个表中没有对应第二个表的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52490414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com