简体   繁体   中英

Create Nested Sub documents/Sub Elements Using MongoDB and Nodejs

I am stuck here. Basically, the requirement is to create a category with 4 levels of sub-category under it in one schema. This should be the approach

Category
|
--Sub Category 
  |
  ---Sub Sub-Category(Sub Category Level 1)
     |
     --------Sub Category Level 2
             |
             ------Sub Category Level 3
                   |
                    ------------ Sub Category Level 4

Image of schema structure for better understanding :

I have created till Category and Sub Category by creating a separate module and CURD data from one Schema.

I have the approach of creating another page for Sub Sub Category. But I think further it might get complicated. If anyone has a better approach please help me with the problem I am facing. Here is the data image from ROBOT 3T

My Robo 3T Example Of Data Category Insert :

My Robo 3T Example Of Data Sub - Category Insert :

Please Help me with a better and dynamic approach. Thank you. :)

We found the solution to this problem by using Embedded/Nested documents method in MongoDB. What we use to do is when we found

I have created two modules for category and sub-category. For category, I used to create the function.

return new Promise(function (resolve, reject) {
let params= JSON.parse(JSON.Stringify(req.body))
categoryModel
        .create(params)
        .then(success => {
           var data = {
              status: 200,
              message: "Record save successfully ",
              data: success
           };
           resolve(data);
        })
        .catch(err => {
           reject(err);
        });
      })

For sub-category, I have used the update function by getting the id of the category(It depends how you do but it is important to get id to update).

return new Promise(function (resolve, reject) {
let id = req.body.id;
let params = re

  categoryModel.update({ _id: id}, 
  { $set: { "sub_category.$.name": "sub_category1", 
          "sub_category.$.type": "video" } })
   .then(success => {
           var data = {
              status: 200,
              message: "Record save successfully ",
              data: success
           };
           resolve(data);
        })
        .catch(err => {
           reject(err);
        });
     })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM