Answer the question
In order to leave comments, you need to log in
How to implement such functionality on MERN?
Good afternoon, there is an online store. Products and their categories. The connection between them is based on the fact that the product has a cateogory property: in which the category ID goes
type: Types.ObjectId,
ref: "Category",
Answer the question
In order to leave comments, you need to log in
I would implement it like this.
Let's say we are using Mongoose . In doing so, we have the Category and Product schemas . One of the Product fields, as you noticed, refers to a Category. In the Category, I would make a virtual "Products", which is an array (a virtual is something that is not stored in the database, but the model fills it, following some logic: here, for example, it will add all the products that refer to it to the array) . Don't forget to create the category "uncategorized"
So. This was the preliminary stage. Now the main thing. When deleting any category, we go through its virtual array "products" and for all products we change the link with this category to the link to the "uncategorized" category. Profit!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question