谁能提供一个简单的多层或无限层分类代码片段?Nodejs+mongodb的。
谁能提供一个简单的多层或无限层分类代码片段?Nodejs+mongodb的。
我对nodejs的控制流程的理解还不够透彻,想用递归的方法实现一个无限层的分类读取。比如:
db | rel | mysql | nosql | mongodb | redis
数据库结构为: { code: “1”, name: “db”, parent: null }
目前,我这里只写了找子分类的代码
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));
})();
代码解释
-
连接到 MongoDB:
- 使用
mongoose.connect
方法连接到本地的 MongoDB 数据库。
- 使用
-
定义分类模型:
- 使用
mongoose.Schema
定义分类模型。模型包括分类的code
,name
, 和parent
(父分类的引用)。
- 使用
-
递归函数
getChildren
:- 这个函数递归地查找指定父分类下的所有子分类,并且使用
populate
方法填充父分类的信息。
- 这个函数递归地查找指定父分类下的所有子分类,并且使用
-
函数
getRootCategories
:- 这个函数查询所有没有父分类的根分类,并通过调用
getChildren
来获取每个根分类的所有子分类。
- 这个函数查询所有没有父分类的根分类,并通过调用
-
测试代码:
- 最后,我们使用
getRootCategories
函数获取所有的根分类及其子分类,并将结果打印出来。
- 最后,我们使用
这个示例展示了如何使用 Node.js 和 MongoDB 实现一个多层级的分类系统。