简体   繁体   中英

How to make parent child schema in mongo db and retrive the data

need help to design and fetch data from MongoDB, the requirement is needed to create a category schema where each category can have multiple child categories and each child category can have further child category and so on, so if in MySQL I have designed it then I can design it like below

category table
id name parent_id

So as you can see the parent_id will be the primary key of the category id and so on, no matter how many children comes it can be handle in it, but I am not getting how to do this in mongo schema as I am new in this db and after making the schema how can I fetch the categories with there children and there children.

There are multiple ways to achieve this but to keep it simple if you want to go with embedding which is best if your category document has limited child and sub-child.

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: 'adsfa',
    childCategories: [
      {
          _id: ObjectId("507f1f77bcf86cd799439012"),
          name: 'asefda',
          childCategories: [
             {
                _id: ObjectId("507f1f77bcf86cd799439013"),
                name: 'afsd',
             },
          ],
      },
    ],
}

As for querying data you'll simply query for parent document _id which will return the whole document with child and all sub child categories. Please do note that this schema might not always be good for you if your child and subchild categories are expected to go on to a large number. In this case you can consider reshaping schema to make use of references. Below is the example for such scenario

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: 'Parent or child category name',
    parent: ObjectId("507f1f77bcf86cd799439012"),
}

In this case you have to use lookups or populates in case of mongoose to fill the data for your parent. But again that totally depends on your use case. So I recommend you read a little about how to structure you document database and pros and cons for each approach.

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