只删除与第二个表相对应的第一个表中没有条目的条目

时间:2018-09-25 04:03:09

标签: javascript mongoose schema

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

我要从类别中删除这两个架构,但是如果我在产品表中具有与该类别相对应的数据,则不应删除该类别。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

它看起来应该像这样:

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

答案 1 :(得分:1)

首先,请像这样更新产品架构中“类别”字段的“类型”属性:

category:{
  type:  Schema.Types.ObjectId,
  ref: 'Category' // model name
}`

并声明如下模型:

var Product = mongoose.model('Product', productSchema );

然后使用“ distinct”查询和“ $ nin” query-operator删除产品架构未引用的类别,例如:

Product.find().distinct('category').then((data)=>{
   Category.deleteMany({_id: {$nin: data}}).then(del => {
       console.log("deleted",del)
   })
})