Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

mongodb - How make this relation in stack MERN?

I have Online Shop, where exists products and category. The product has in model field

 category: {
    type: Types.ObjectId,
    ref: "Category",
    required: [true, "Product category is required"]
  },

and when i add new product select category ( in list exists ) and add id.

But if remove category, the products have categoryId which does not exists. Is it possible to implement the functionality that used in wordpress. For example if in wordpress i remove category, all posts who had this category, transfer in category uncategorized (This category create automatically and cannot be delete)

question from:https://stackoverflow.com/questions/65713486/how-make-this-relation-in-stack-mern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understood you correctly, you can use mongoose middlewares to "cascade deleting". So when a category is removed, you can to code that every product has now "Uncategorized"

You can use a pre hook when you call delete function and do something like this (not tested with your schema):

category.pre(/(?:delete|remove)/, function(next) {
    var id = this.getQuery()._id; //get category _id
    product.updateMany({
      category: id
    },{
      $set:{
        category:yourUncategorizedId
      }
    }).then(next()).catch(e => next(e))
})

So, in this case, a regex match is used to go into the hook.

This hook is called when a remove or delete function is called from category model. So, when a category is deleted, this hook will update all references by your uncategorizedId to ensure any product has a non-existing category reference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...