谁能提供一个简单的多层或无限层分类代码片段?Nodejs+mongodb的。

谁能提供一个简单的多层或无限层分类代码片段?Nodejs+mongodb的。

我对nodejs的控制流程的理解还不够透彻,想用递归的方法实现一个无限层的分类读取。比如:

db | rel | mysql | nosql | mongodb | redis

数据库结构为: { code: “1”, name: “db”, parent: null }

3 回复

当然可以!为了实现一个多层或无限层分类的功能,我们可以使用递归来处理嵌套的数据结构。下面是一个简单的示例,展示了如何在Node.js中使用MongoDB来实现这样的功能。

首先,我们需要设置一个基本的MongoDB模型,用于存储分类数据。然后,我们将编写一个函数来递归地获取所有子分类。

数据库模型

假设我们有一个名为 Category 的集合,其中每个文档都有以下字段:

  • code: 分类的唯一标识符
  • name: 分类的名称
  • parent: 父分类的 code(如果有的话)
const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
    code: { type: String, required: true, unique: true },
    name: { type: String, required: true },
    parent: { type: String }
});

const Category = mongoose.model('Category', categorySchema);

获取分类树

接下来,我们将编写一个递归函数来获取所有子分类。这个函数将接受一个分类代码,并返回该分类及其所有子分类。

async function getCategoriesTree(parentCode) {
    const categories = await Category.find({ parent: parentCode }).lean();
    
    for (let category of categories) {
        category.children = await getCategoriesTree(category.code);
    }

    return categories;
}

示例用法

现在,我们可以调用 getCategoriesTree 函数来获取分类树。例如,如果我们想要获取顶级分类及其所有子分类,可以这样做:

(async () => {
    try {
        const db = await mongoose.connect('mongodb://localhost:27017/your_database_name');
        
        const topLevelCategories = await getCategoriesTree(null);
        console.log(JSON.stringify(topLevelCategories, null, 2));
    } catch (error) {
        console.error(error);
    }
})();

在这个例子中,getCategoriesTree(null) 将从没有父分类的顶级分类开始,递归地获取所有子分类。

解释

  1. 数据库模型:我们定义了一个简单的Mongoose模型来表示分类。
  2. 递归函数getCategoriesTree 函数通过查找具有指定父分类代码的所有子分类来构建分类树。它递归地调用自身以获取每个子分类的所有子分类。
  3. 示例用法:我们连接到MongoDB数据库并调用 getCategoriesTree 函数来获取顶级分类及其所有子分类。

这样,你就可以轻松地获取一个多层分类结构,并且可以通过递归处理任意深度的嵌套分类。


目前,我这里只写了找子分类的代码

Cate.findByParent = function(parent, callback){ mongodb.open(function(err, db){ if (err){ return callback(err); } db.collection(‘cates’, function(err, collection){ if (err){ mongodb.close(); return callback(err); }

collection.find({parent: parent}).toArray(function(err, cates){ mongodb.close(); if(err){ return callback(err); } callback(null, cates); }); }); }); };

示例代码

为了实现一个无限层级的分类系统,我们可以使用递归来处理树形数据结构。以下是一个简单的示例代码,展示如何在 Node.js 中与 MongoDB 结合来实现这一功能。

首先确保已经安装了 mongoose

npm install mongoose

接下来是具体的代码实现:

const mongoose = require('mongoose');

// 连接到 MongoDB
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });

// 定义分类模型
const CategorySchema = new mongoose.Schema({
    code: String,
    name: String,
    parent: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
});

const Category = mongoose.model('Category', CategorySchema);

// 递归函数用于获取所有子分类
async function getChildren(parentId) {
    const children = await Category.find({ parent: parentId }).populate('parent');
    for (let child of children) {
        child.children = await getChildren(child._id);
    }
    return children;
}

// 获取根分类
async function getRootCategories() {
    const rootCategories = await Category.find({ parent: null });
    for (let category of rootCategories) {
        category.children = await getChildren(category._id);
    }
    return rootCategories;
}

// 测试代码
(async () => {
    const categories = await getRootCategories();
    console.log(JSON.stringify(categories, null, 2));
})();

代码解释

  1. 连接到 MongoDB:

    • 使用 mongoose.connect 方法连接到本地的 MongoDB 数据库。
  2. 定义分类模型:

    • 使用 mongoose.Schema 定义分类模型。模型包括分类的 code, name, 和 parent(父分类的引用)。
  3. 递归函数 getChildren:

    • 这个函数递归地查找指定父分类下的所有子分类,并且使用 populate 方法填充父分类的信息。
  4. 函数 getRootCategories:

    • 这个函数查询所有没有父分类的根分类,并通过调用 getChildren 来获取每个根分类的所有子分类。
  5. 测试代码:

    • 最后,我们使用 getRootCategories 函数获取所有的根分类及其子分类,并将结果打印出来。

这个示例展示了如何使用 Node.js 和 MongoDB 实现一个多层级的分类系统。

回到顶部