递归填充父级n级

发布于 2025-02-11 07:48:54 字数 22339 浏览 2 评论 0原文

我有一个看起来像这样的类别模型,

const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const category = {
  name: {
    type: String,
    required: true,
    trim: true,
    max: 32,
    unique: true,
  },
  subCategories: [
    {
      type: Schema.Types.ObjectId,
      ref: "Category",
    },
  ],
  parent: {
    type: Schema.Types.ObjectId,
    ref: "Category",
  },
  products: [
    {
      type: ObjectId,
      ref: "Product",
    },
  ],
  slug: {
    type: String,
    required: "URL can't be empty",
    unique: true,
  },
};
const categorySchema = new Schema(category, { timestamps: true });
//Validate the slug to ensure proper url is given
categorySchema.path("slug").validate((val) => {
  urlRegex =
    /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
  return urlRegex.test(val);
}, "Invalid URL.");
const autoPopulateChildren = function (next) {
  this.populate("subCategories");
  next();
};
categorySchema
  .pre("findOne", autoPopulateChildren)
  .pre("findById", autoPopulateChildren)
  .pre("find", autoPopulateChildren);
const Category = mongoose.model("Category", categorySchema);
module.exports = Category;

我想递归地填充其父母。

现在,

Main
  -> Computers & Accessories
    -> Components
     -> Motherboard

当我查询主板类别时,我有一个看起来像这样的数据,我希望它退还其所有父母(一直到主要类别)。像这样的事情

{
    "subCategories": [],
    "products": [],
    "_id": "62baca1a1ffdc142085bca80",
    "name": "Motherboard",
    "parent": {
        "subCategories": [
            {
                "subCategories": [],
                "products": [],
                "_id": "62baca1a1ffdc142085bca80",
                "name": "Motherboard",
                "parent": "62bac5af6b6581786cb192e4",
                "slug": "http://localhost:4007/category/motherboard",
                "createdAt": "2022-06-28T09:30:02.040Z",
                "updatedAt": "2022-06-28T09:30:02.040Z",
                "__v": 0
            },
            {
                "subCategories": [],
                "products": [],
                "_id": "62bac9a24bd73045dcb563d7",
                "name": "RAM",
                "parent": "62bac5af6b6581786cb192e4",
                "slug": "http://localhost:4007/category/ram",
                "createdAt": "2022-06-28T09:28:02.643Z",
                "updatedAt": "2022-06-28T09:28:02.643Z",
                "__v": 0
            }
        ],
        "products": [],
        "_id": "62bac5af6b6581786cb192e4",
        "name": "components",
        "parent": {
            "subCategories": [
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62baca1a1ffdc142085bca80",
                            "name": "Motherboard",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/motherboard",
                            "createdAt": "2022-06-28T09:30:02.040Z",
                            "updatedAt": "2022-06-28T09:30:02.040Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bac9a24bd73045dcb563d7",
                            "name": "RAM",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/ram",
                            "createdAt": "2022-06-28T09:28:02.643Z",
                            "updatedAt": "2022-06-28T09:28:02.643Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac5af6b6581786cb192e4",
                    "name": "components",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007/category/components",
                    "createdAt": "2022-06-28T09:11:11.226Z",
                    "updatedAt": "2022-06-28T09:11:11.226Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacae4da4c372c48c4a996",
                            "name": "Huawei",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/huawei",
                            "createdAt": "2022-06-28T09:33:24.218Z",
                            "updatedAt": "2022-06-28T09:33:24.218Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb137e6e0b6ac850b9ce",
                            "name": "Apple",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/apple",
                            "createdAt": "2022-06-28T09:34:11.549Z",
                            "updatedAt": "2022-06-28T09:34:11.549Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac6696b6581786cb192e7",
                    "name": "laptop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/laptop",
                    "createdAt": "2022-06-28T09:14:17.650Z",
                    "updatedAt": "2022-06-28T09:14:17.650Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb65045848303cd21b67",
                            "name": "Gaming",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/gaming",
                            "createdAt": "2022-06-28T09:35:33.414Z",
                            "updatedAt": "2022-06-28T09:35:33.414Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacc72e84e007314a97abe",
                            "name": "DIY",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/diy",
                            "createdAt": "2022-06-28T09:40:02.359Z",
                            "updatedAt": "2022-06-28T09:40:02.359Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac8016b6581786cb192f0",
                    "name": "Desktop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/components",
                    "createdAt": "2022-06-28T09:21:05.807Z",
                    "updatedAt": "2022-06-28T09:21:05.807Z",
                    "__v": 0
                }
            ],
            "products": [],
            "_id": "62bac35ba30786989841809b",
            "name": "Computers & Accessories",
            "parent": {
                "subCategories": [
                    {
                        "subCategories": [
                            {
                                "subCategories": [
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62baca1a1ffdc142085bca80",
                                        "name": "Motherboard",
                                        "parent": "62bac5af6b6581786cb192e4",
                                        "slug": "http://localhost:4007/category/motherboard",
                                        "createdAt": "2022-06-28T09:30:02.040Z",
                                        "updatedAt": "2022-06-28T09:30:02.040Z",
                                        "__v": 0
                                    },
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bac9a24bd73045dcb563d7",
                                        "name": "RAM",
                                        "parent": "62bac5af6b6581786cb192e4",
                                        "slug": "http://localhost:4007/category/ram",
                                        "createdAt": "2022-06-28T09:28:02.643Z",
                                        "updatedAt": "2022-06-28T09:28:02.643Z",
                                        "__v": 0
                                    }
                                ],
                                "products": [],
                                "_id": "62bac5af6b6581786cb192e4",
                                "name": "components",
                                "parent": "62bac35ba30786989841809b",
                                "slug": "http://localhost:4007/category/components",
                                "createdAt": "2022-06-28T09:11:11.226Z",
                                "updatedAt": "2022-06-28T09:11:11.226Z",
                                "__v": 0
                            },
                            {
                                "subCategories": [
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacae4da4c372c48c4a996",
                                        "name": "Huawei",
                                        "parent": "62bac6696b6581786cb192e7",
                                        "slug": "http://localhost:4007/category/huawei",
                                        "createdAt": "2022-06-28T09:33:24.218Z",
                                        "updatedAt": "2022-06-28T09:33:24.218Z",
                                        "__v": 0
                                    },
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacb137e6e0b6ac850b9ce",
                                        "name": "Apple",
                                        "parent": "62bac6696b6581786cb192e7",
                                        "slug": "http://localhost:4007/category/apple",
                                        "createdAt": "2022-06-28T09:34:11.549Z",
                                        "updatedAt": "2022-06-28T09:34:11.549Z",
                                        "__v": 0
                                    }
                                ],
                                "products": [],
                                "_id": "62bac6696b6581786cb192e7",
                                "name": "laptop",
                                "parent": "62bac35ba30786989841809b",
                                "slug": "http://localhost:4007//category/laptop",
                                "createdAt": "2022-06-28T09:14:17.650Z",
                                "updatedAt": "2022-06-28T09:14:17.650Z",
                                "__v": 0
                            },
                            {
                                "subCategories": [
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacb65045848303cd21b67",
                                        "name": "Gaming",
                                        "parent": "62bac8016b6581786cb192f0",
                                        "slug": "http://localhost:4007/category/gaming",
                                        "createdAt": "2022-06-28T09:35:33.414Z",
                                        "updatedAt": "2022-06-28T09:35:33.414Z",
                                        "__v": 0
                                    },
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacc72e84e007314a97abe",
                                        "name": "DIY",
                                        "parent": "62bac8016b6581786cb192f0",
                                        "slug": "http://localhost:4007/category/diy",
                                        "createdAt": "2022-06-28T09:40:02.359Z",
                                        "updatedAt": "2022-06-28T09:40:02.359Z",
                                        "__v": 0
                                    }
                                ],
                                "products": [],
                                "_id": "62bac8016b6581786cb192f0",
                                "name": "Desktop",
                                "parent": "62bac35ba30786989841809b",
                                "slug": "http://localhost:4007//category/components",
                                "createdAt": "2022-06-28T09:21:05.807Z",
                                "updatedAt": "2022-06-28T09:21:05.807Z",
                                "__v": 0
                            }
                        ],
                        "products": [],
                        "_id": "62bac35ba30786989841809b",
                        "name": "Computers & Accessories",
                        "parent": "62bac6eddfe90a7c09873d92",
                        "slug": "http://localhost:4007/category/computers&accessories",
                        "createdAt": "2022-06-28T09:01:15.666Z",
                        "updatedAt": "2022-06-28T09:01:15.666Z",
                        "__v": 0
                    }
                ],
                "products": [],
                "_id": "62bac6eddfe90a7c09873d92",
                "name": "Main Shop Name",
                "parent": null,
                "slug": "http://localhost:4007/category/main",
                "createdAt": "2022-06-28T09:01:15.666Z",
                "updatedAt": "2022-06-28T09:01:15.666Z",
                "__v": 0
            },
            "slug": "http://localhost:4007/category/computers&accessories",
            "createdAt": "2022-06-28T09:01:15.666Z",
            "updatedAt": "2022-06-28T09:01:15.666Z",
            "__v": 0
        },
        "slug": "http://localhost:4007/category/components",
        "createdAt": "2022-06-28T09:11:11.226Z",
        "updatedAt": "2022-06-28T09:11:11.226Z",
        "__v": 0
    },
    "slug": "http://localhost:4007/category/motherboard",
    "createdAt": "2022-06-28T09:30:02.040Z",
    "updatedAt": "2022-06-28T09:30:02.040Z",
    "__v": 0
}

是我的代码,

const populateParents = async (node) => {
  if (node.parent) {
    let newNode = await Category.populate(node, { path: "parent" });
    return populateParents(newNode.parent);
  }
  return node;
};

//Routes
router.get("/categories/:categoryId", [RequireSignIn], async (req, res) => {
  try {
    const { categoryId } = req.params;
    const category = await Category.findOne({ _id: categoryId });
    const populatedCategories = await populateParents(category);
    return res.status(200).send(populatedCategories);
  } catch (error) {
    return res.status(500).send(error);
  }
});

我回来只是响应的主要类别。

{
    "subCategories": [
        {
            "subCategories": [
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62baca1a1ffdc142085bca80",
                            "name": "Motherboard",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/motherboard",
                            "createdAt": "2022-06-28T09:30:02.040Z",
                            "updatedAt": "2022-06-28T09:30:02.040Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bac9a24bd73045dcb563d7",
                            "name": "RAM",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/ram",
                            "createdAt": "2022-06-28T09:28:02.643Z",
                            "updatedAt": "2022-06-28T09:28:02.643Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac5af6b6581786cb192e4",
                    "name": "components",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007/category/components",
                    "createdAt": "2022-06-28T09:11:11.226Z",
                    "updatedAt": "2022-06-28T09:11:11.226Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacae4da4c372c48c4a996",
                            "name": "Huawei",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/huawei",
                            "createdAt": "2022-06-28T09:33:24.218Z",
                            "updatedAt": "2022-06-28T09:33:24.218Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb137e6e0b6ac850b9ce",
                            "name": "Apple",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/apple",
                            "createdAt": "2022-06-28T09:34:11.549Z",
                            "updatedAt": "2022-06-28T09:34:11.549Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac6696b6581786cb192e7",
                    "name": "laptop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/laptop",
                    "createdAt": "2022-06-28T09:14:17.650Z",
                    "updatedAt": "2022-06-28T09:14:17.650Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb65045848303cd21b67",
                            "name": "Gaming",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/gaming",
                            "createdAt": "2022-06-28T09:35:33.414Z",
                            "updatedAt": "2022-06-28T09:35:33.414Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacc72e84e007314a97abe",
                            "name": "DIY",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/diy",
                            "createdAt": "2022-06-28T09:40:02.359Z",
                            "updatedAt": "2022-06-28T09:40:02.359Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac8016b6581786cb192f0",
                    "name": "Desktop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/components",
                    "createdAt": "2022-06-28T09:21:05.807Z",
                    "updatedAt": "2022-06-28T09:21:05.807Z",
                    "__v": 0
                }
            ],
            "products": [],
            "_id": "62bac35ba30786989841809b",
            "name": "Computers & Accessories",
            "parent": "62bac6eddfe90a7c09873d92",
            "slug": "http://localhost:4007/category/computers&accessories",
            "createdAt": "2022-06-28T09:01:15.666Z",
            "updatedAt": "2022-06-28T09:01:15.666Z",
            "__v": 0
        }
    ],
    "products": [],
    "_id": "62bac6eddfe90a7c09873d92",
    "name": "Main Shop Name",
    "parent": null,
    "slug": "http://localhost:4007/category/main",
    "createdAt": "2022-06-28T09:01:15.666Z",
    "updatedAt": "2022-06-28T09:01:15.666Z",
    "__v": 0
}

如果我不递归编写功能,那么

const populateParents2 = async (node) => {
  const newNode = await Category.populate(node, { path: "parent" });
  const newNode2 = await Category.populate(newNode.parent, { path: "parent" });
  const newNode3 = await Category.populate(newNode2.parent, { path: "parent" });
  return newNode;
};

如果有人可以指出如何递归写作功能或有其他更好的方法来做这件事,

请感谢您的效果

I have a category Model which looks like this

const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const category = {
  name: {
    type: String,
    required: true,
    trim: true,
    max: 32,
    unique: true,
  },
  subCategories: [
    {
      type: Schema.Types.ObjectId,
      ref: "Category",
    },
  ],
  parent: {
    type: Schema.Types.ObjectId,
    ref: "Category",
  },
  products: [
    {
      type: ObjectId,
      ref: "Product",
    },
  ],
  slug: {
    type: String,
    required: "URL can't be empty",
    unique: true,
  },
};
const categorySchema = new Schema(category, { timestamps: true });
//Validate the slug to ensure proper url is given
categorySchema.path("slug").validate((val) => {
  urlRegex =
    /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
  return urlRegex.test(val);
}, "Invalid URL.");
const autoPopulateChildren = function (next) {
  this.populate("subCategories");
  next();
};
categorySchema
  .pre("findOne", autoPopulateChildren)
  .pre("findById", autoPopulateChildren)
  .pre("find", autoPopulateChildren);
const Category = mongoose.model("Category", categorySchema);
module.exports = Category;

I would like to recursively populate its parent.

Right now, I have a data that looks like this

Main
  -> Computers & Accessories
    -> Components
     -> Motherboard

When I query Motherboard category, I would like it to return back all its parents (all the way up to Main category). Something like this

{
    "subCategories": [],
    "products": [],
    "_id": "62baca1a1ffdc142085bca80",
    "name": "Motherboard",
    "parent": {
        "subCategories": [
            {
                "subCategories": [],
                "products": [],
                "_id": "62baca1a1ffdc142085bca80",
                "name": "Motherboard",
                "parent": "62bac5af6b6581786cb192e4",
                "slug": "http://localhost:4007/category/motherboard",
                "createdAt": "2022-06-28T09:30:02.040Z",
                "updatedAt": "2022-06-28T09:30:02.040Z",
                "__v": 0
            },
            {
                "subCategories": [],
                "products": [],
                "_id": "62bac9a24bd73045dcb563d7",
                "name": "RAM",
                "parent": "62bac5af6b6581786cb192e4",
                "slug": "http://localhost:4007/category/ram",
                "createdAt": "2022-06-28T09:28:02.643Z",
                "updatedAt": "2022-06-28T09:28:02.643Z",
                "__v": 0
            }
        ],
        "products": [],
        "_id": "62bac5af6b6581786cb192e4",
        "name": "components",
        "parent": {
            "subCategories": [
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62baca1a1ffdc142085bca80",
                            "name": "Motherboard",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/motherboard",
                            "createdAt": "2022-06-28T09:30:02.040Z",
                            "updatedAt": "2022-06-28T09:30:02.040Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bac9a24bd73045dcb563d7",
                            "name": "RAM",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/ram",
                            "createdAt": "2022-06-28T09:28:02.643Z",
                            "updatedAt": "2022-06-28T09:28:02.643Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac5af6b6581786cb192e4",
                    "name": "components",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007/category/components",
                    "createdAt": "2022-06-28T09:11:11.226Z",
                    "updatedAt": "2022-06-28T09:11:11.226Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacae4da4c372c48c4a996",
                            "name": "Huawei",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/huawei",
                            "createdAt": "2022-06-28T09:33:24.218Z",
                            "updatedAt": "2022-06-28T09:33:24.218Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb137e6e0b6ac850b9ce",
                            "name": "Apple",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/apple",
                            "createdAt": "2022-06-28T09:34:11.549Z",
                            "updatedAt": "2022-06-28T09:34:11.549Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac6696b6581786cb192e7",
                    "name": "laptop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/laptop",
                    "createdAt": "2022-06-28T09:14:17.650Z",
                    "updatedAt": "2022-06-28T09:14:17.650Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb65045848303cd21b67",
                            "name": "Gaming",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/gaming",
                            "createdAt": "2022-06-28T09:35:33.414Z",
                            "updatedAt": "2022-06-28T09:35:33.414Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacc72e84e007314a97abe",
                            "name": "DIY",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/diy",
                            "createdAt": "2022-06-28T09:40:02.359Z",
                            "updatedAt": "2022-06-28T09:40:02.359Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac8016b6581786cb192f0",
                    "name": "Desktop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/components",
                    "createdAt": "2022-06-28T09:21:05.807Z",
                    "updatedAt": "2022-06-28T09:21:05.807Z",
                    "__v": 0
                }
            ],
            "products": [],
            "_id": "62bac35ba30786989841809b",
            "name": "Computers & Accessories",
            "parent": {
                "subCategories": [
                    {
                        "subCategories": [
                            {
                                "subCategories": [
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62baca1a1ffdc142085bca80",
                                        "name": "Motherboard",
                                        "parent": "62bac5af6b6581786cb192e4",
                                        "slug": "http://localhost:4007/category/motherboard",
                                        "createdAt": "2022-06-28T09:30:02.040Z",
                                        "updatedAt": "2022-06-28T09:30:02.040Z",
                                        "__v": 0
                                    },
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bac9a24bd73045dcb563d7",
                                        "name": "RAM",
                                        "parent": "62bac5af6b6581786cb192e4",
                                        "slug": "http://localhost:4007/category/ram",
                                        "createdAt": "2022-06-28T09:28:02.643Z",
                                        "updatedAt": "2022-06-28T09:28:02.643Z",
                                        "__v": 0
                                    }
                                ],
                                "products": [],
                                "_id": "62bac5af6b6581786cb192e4",
                                "name": "components",
                                "parent": "62bac35ba30786989841809b",
                                "slug": "http://localhost:4007/category/components",
                                "createdAt": "2022-06-28T09:11:11.226Z",
                                "updatedAt": "2022-06-28T09:11:11.226Z",
                                "__v": 0
                            },
                            {
                                "subCategories": [
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacae4da4c372c48c4a996",
                                        "name": "Huawei",
                                        "parent": "62bac6696b6581786cb192e7",
                                        "slug": "http://localhost:4007/category/huawei",
                                        "createdAt": "2022-06-28T09:33:24.218Z",
                                        "updatedAt": "2022-06-28T09:33:24.218Z",
                                        "__v": 0
                                    },
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacb137e6e0b6ac850b9ce",
                                        "name": "Apple",
                                        "parent": "62bac6696b6581786cb192e7",
                                        "slug": "http://localhost:4007/category/apple",
                                        "createdAt": "2022-06-28T09:34:11.549Z",
                                        "updatedAt": "2022-06-28T09:34:11.549Z",
                                        "__v": 0
                                    }
                                ],
                                "products": [],
                                "_id": "62bac6696b6581786cb192e7",
                                "name": "laptop",
                                "parent": "62bac35ba30786989841809b",
                                "slug": "http://localhost:4007//category/laptop",
                                "createdAt": "2022-06-28T09:14:17.650Z",
                                "updatedAt": "2022-06-28T09:14:17.650Z",
                                "__v": 0
                            },
                            {
                                "subCategories": [
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacb65045848303cd21b67",
                                        "name": "Gaming",
                                        "parent": "62bac8016b6581786cb192f0",
                                        "slug": "http://localhost:4007/category/gaming",
                                        "createdAt": "2022-06-28T09:35:33.414Z",
                                        "updatedAt": "2022-06-28T09:35:33.414Z",
                                        "__v": 0
                                    },
                                    {
                                        "subCategories": [],
                                        "products": [],
                                        "_id": "62bacc72e84e007314a97abe",
                                        "name": "DIY",
                                        "parent": "62bac8016b6581786cb192f0",
                                        "slug": "http://localhost:4007/category/diy",
                                        "createdAt": "2022-06-28T09:40:02.359Z",
                                        "updatedAt": "2022-06-28T09:40:02.359Z",
                                        "__v": 0
                                    }
                                ],
                                "products": [],
                                "_id": "62bac8016b6581786cb192f0",
                                "name": "Desktop",
                                "parent": "62bac35ba30786989841809b",
                                "slug": "http://localhost:4007//category/components",
                                "createdAt": "2022-06-28T09:21:05.807Z",
                                "updatedAt": "2022-06-28T09:21:05.807Z",
                                "__v": 0
                            }
                        ],
                        "products": [],
                        "_id": "62bac35ba30786989841809b",
                        "name": "Computers & Accessories",
                        "parent": "62bac6eddfe90a7c09873d92",
                        "slug": "http://localhost:4007/category/computers&accessories",
                        "createdAt": "2022-06-28T09:01:15.666Z",
                        "updatedAt": "2022-06-28T09:01:15.666Z",
                        "__v": 0
                    }
                ],
                "products": [],
                "_id": "62bac6eddfe90a7c09873d92",
                "name": "Main Shop Name",
                "parent": null,
                "slug": "http://localhost:4007/category/main",
                "createdAt": "2022-06-28T09:01:15.666Z",
                "updatedAt": "2022-06-28T09:01:15.666Z",
                "__v": 0
            },
            "slug": "http://localhost:4007/category/computers&accessories",
            "createdAt": "2022-06-28T09:01:15.666Z",
            "updatedAt": "2022-06-28T09:01:15.666Z",
            "__v": 0
        },
        "slug": "http://localhost:4007/category/components",
        "createdAt": "2022-06-28T09:11:11.226Z",
        "updatedAt": "2022-06-28T09:11:11.226Z",
        "__v": 0
    },
    "slug": "http://localhost:4007/category/motherboard",
    "createdAt": "2022-06-28T09:30:02.040Z",
    "updatedAt": "2022-06-28T09:30:02.040Z",
    "__v": 0
}

Following is my code

const populateParents = async (node) => {
  if (node.parent) {
    let newNode = await Category.populate(node, { path: "parent" });
    return populateParents(newNode.parent);
  }
  return node;
};

//Routes
router.get("/categories/:categoryId", [RequireSignIn], async (req, res) => {
  try {
    const { categoryId } = req.params;
    const category = await Category.findOne({ _id: categoryId });
    const populatedCategories = await populateParents(category);
    return res.status(200).send(populatedCategories);
  } catch (error) {
    return res.status(500).send(error);
  }
});

What I am getting back is only the Main category in response.

{
    "subCategories": [
        {
            "subCategories": [
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62baca1a1ffdc142085bca80",
                            "name": "Motherboard",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/motherboard",
                            "createdAt": "2022-06-28T09:30:02.040Z",
                            "updatedAt": "2022-06-28T09:30:02.040Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bac9a24bd73045dcb563d7",
                            "name": "RAM",
                            "parent": "62bac5af6b6581786cb192e4",
                            "slug": "http://localhost:4007/category/ram",
                            "createdAt": "2022-06-28T09:28:02.643Z",
                            "updatedAt": "2022-06-28T09:28:02.643Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac5af6b6581786cb192e4",
                    "name": "components",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007/category/components",
                    "createdAt": "2022-06-28T09:11:11.226Z",
                    "updatedAt": "2022-06-28T09:11:11.226Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacae4da4c372c48c4a996",
                            "name": "Huawei",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/huawei",
                            "createdAt": "2022-06-28T09:33:24.218Z",
                            "updatedAt": "2022-06-28T09:33:24.218Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb137e6e0b6ac850b9ce",
                            "name": "Apple",
                            "parent": "62bac6696b6581786cb192e7",
                            "slug": "http://localhost:4007/category/apple",
                            "createdAt": "2022-06-28T09:34:11.549Z",
                            "updatedAt": "2022-06-28T09:34:11.549Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac6696b6581786cb192e7",
                    "name": "laptop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/laptop",
                    "createdAt": "2022-06-28T09:14:17.650Z",
                    "updatedAt": "2022-06-28T09:14:17.650Z",
                    "__v": 0
                },
                {
                    "subCategories": [
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacb65045848303cd21b67",
                            "name": "Gaming",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/gaming",
                            "createdAt": "2022-06-28T09:35:33.414Z",
                            "updatedAt": "2022-06-28T09:35:33.414Z",
                            "__v": 0
                        },
                        {
                            "subCategories": [],
                            "products": [],
                            "_id": "62bacc72e84e007314a97abe",
                            "name": "DIY",
                            "parent": "62bac8016b6581786cb192f0",
                            "slug": "http://localhost:4007/category/diy",
                            "createdAt": "2022-06-28T09:40:02.359Z",
                            "updatedAt": "2022-06-28T09:40:02.359Z",
                            "__v": 0
                        }
                    ],
                    "products": [],
                    "_id": "62bac8016b6581786cb192f0",
                    "name": "Desktop",
                    "parent": "62bac35ba30786989841809b",
                    "slug": "http://localhost:4007//category/components",
                    "createdAt": "2022-06-28T09:21:05.807Z",
                    "updatedAt": "2022-06-28T09:21:05.807Z",
                    "__v": 0
                }
            ],
            "products": [],
            "_id": "62bac35ba30786989841809b",
            "name": "Computers & Accessories",
            "parent": "62bac6eddfe90a7c09873d92",
            "slug": "http://localhost:4007/category/computers&accessories",
            "createdAt": "2022-06-28T09:01:15.666Z",
            "updatedAt": "2022-06-28T09:01:15.666Z",
            "__v": 0
        }
    ],
    "products": [],
    "_id": "62bac6eddfe90a7c09873d92",
    "name": "Main Shop Name",
    "parent": null,
    "slug": "http://localhost:4007/category/main",
    "createdAt": "2022-06-28T09:01:15.666Z",
    "updatedAt": "2022-06-28T09:01:15.666Z",
    "__v": 0
}

If I write the function without recursion , it works

const populateParents2 = async (node) => {
  const newNode = await Category.populate(node, { path: "parent" });
  const newNode2 = await Category.populate(newNode.parent, { path: "parent" });
  const newNode3 = await Category.populate(newNode2.parent, { path: "parent" });
  return newNode;
};

So appreciate if someone can point out how to write populateParents function recursively or is there another better way to do this

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

去了角落 2025-02-18 07:48:54

与此问题非常相似的问题

Comment12858464640_72798639找到了这个问题的解决方案

const populateParents = async (node) => {
  if (node.parent === null) {
    return node;
  }
  const parent = await Category.findById(node.parent).select("-subCategories");
  node.parent = parent;
  await populateParents(node.parent);
  return node;
};

//Routes
router.get("/categories/:categoryId", async (req, res) => {
  try {
    const { categoryId } = req.params;
    const category = await Category.findOne({ _id: categoryId }).select(
      "-subCategories"
    );
    const populatedCategories = await populateParents(category);
    return res.status(200).send(populatedCategories);
  } catch (error) {
    return res.status(500).send(error);
  }
});

Question very similar to this question Create a deeply nested object

Btw found the solution for this question

const populateParents = async (node) => {
  if (node.parent === null) {
    return node;
  }
  const parent = await Category.findById(node.parent).select("-subCategories");
  node.parent = parent;
  await populateParents(node.parent);
  return node;
};

//Routes
router.get("/categories/:categoryId", async (req, res) => {
  try {
    const { categoryId } = req.params;
    const category = await Category.findOne({ _id: categoryId }).select(
      "-subCategories"
    );
    const populatedCategories = await populateParents(category);
    return res.status(200).send(populatedCategories);
  } catch (error) {
    return res.status(500).send(error);
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文