【问题标题】:Mongodb unlimited nested category, sub-category and sub-sub-category and so onMongodb无限嵌套类、子类和子子类等
【发布时间】:2022-03-15 18:12:57
【问题描述】:

我创建了一个电子商务网站,但想更改它的一些功能,我希望允许用户创建无限的类别和子类别。最好的方法是什么?我使用了 Nodejs (express) 和 MongoDB (mongoose)。 目前,数据库架构是这样的:

category.js

const mongoose = require('mongoose');
const { s, rs, n, ref } = require('../utils/mongo');

var schema = new mongoose.Schema(
  {
    user: ref('user'),
    name: { ...rs, unique: true },
    description: s,
    image: s,
    view: {
      ...n,
      default: 0,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model('category', schema);

subcategory.js

const mongoose = require('mongoose');
const { s, rs, ref } = require('../utils/mongo');

var schema = new mongoose.Schema(
  {
    category: ref('category'),
    name: { ...rs, unique: true },
    description: s,
  },
  { timestamps: true }
);

module.exports = mongoose.model('subcategory', schema);

提前欣赏

【问题讨论】:

  • 目前我只有一个分类和一个子分类,我想改成无限嵌套分类
  • 您可以只引用另一个类别而不是子类别 - 并删除子类别架构。这样您就可以拥有深度嵌套的子类别。

标签: node.js mongodb express mongoose nested


【解决方案1】:

只使用一个模型

import mongoose from "mongoose";

const CategorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    parent_id: {
        type: mongoose.Schema.Types.ObjectId,
        default: null
    },
    description: {
        type: String,
        default: null
    },
    image: {
        url: String,
        public_id: String
    },
});

export mongoose.model('Category', CategorySchema);

// Create category
import { Category } from "./model/category.model"
const createCategory = async (data) => {
    try {
        return await new Category(data).save()
    } catch (err) {
        console.log(err)
    }
}

// Get all category
const getAllCategory = async () => {
    try {
        const categories = await Category.find({});
        if (!categories) return [];
        return nestedCategories(categories);
    } catch (err) {
        console.log(err);
    }
}

function nestedCategories(categories, parentId = null) {
    const categoryList = [];
    let category;
    if (parentId == null) {
        category = categories.filter(cat => cat.parent_id == null);
    } else {
        category = categories.filter(cat => String(cat.parent_id) == String(parentId));
    }

    for (let cate of category) {
        categoryList.push({
            _id: cate._id,
            name: cate.name,
            slug: cate.slug,
            children: nestedCategories(categories, cate._id)
        })
    }
    return categoryList;
}

【讨论】:

    【解决方案2】:

    如果您想要无限的嵌套类别,您只需要一个类别架构。

    let schema = new mongoose.Schema(
      {
        user: ref('user'),
        name: { ...rs, unique: true },
        description: s,
        image: s,
        parent: { type: mongoose.Schema.Types.ObjectId }, //the parent category
        view: {
          ...n,
          default: 0,
        },
      },
      { timestamps: true }
    );
    
    module.exports = mongoose.model('category', schema);
    

    很遗憾,您不能在不指定特定级别的情况下使用populate$lookup,因此如果您需要无限嵌套,则需要自己构建树。

    【讨论】:

    • 老兄,我想创建一个无限嵌套的类别。找不到所有者的记录
    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2019-02-26
    • 2017-06-03
    • 2014-10-03
    • 2014-07-02
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多