D
D
DeniSidorenko2021-01-14 07:32:12
MongoDB
DeniSidorenko, 2021-01-14 07:32:12

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",


Now I noticed such a feature that when deleting a category, the product has a category id that does not exist. In this case, the WordPress developers did a good job, they always have an Uncategorized category (uncategorized ) that cannot be deleted. And if a category is deleted, the posts are automatically applied to that category. Is it possible to replicate this functionality here as well?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valery Kulakov, 2021-01-14
@DeniSidorenko

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!

V
Vladislav, 2021-01-14
@cr1gger

the answer is unequivocal. Maybe!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question