Nodejs 能给个树形菜单的参考吗?节点存放在mongodb,使用mongoskin取出节点并递归子节点,生成一个json数据。

Nodejs 能给个树形菜单的参考吗?节点存放在mongodb,使用mongoskin取出节点并递归子节点,生成一个json数据。

mongodb如何做树的遍历!!

2 回复

当然可以!下面是一个简单的例子,展示如何使用 Node.js 和 MongoDB(通过 mongoskin)来获取树形结构的数据,并将其转换为 JSON 格式。

步骤概述

  1. 安装依赖:确保你已经安装了 mongoskinexpress(如果你打算使用 Express 框架)。
  2. 连接到 MongoDB:创建一个数据库连接。
  3. 查询数据:从 MongoDB 中获取树形结构的数据。
  4. 递归处理:将数据递归地转换成树形结构的 JSON 数据。

示例代码

1. 安装依赖

npm install mongoskin express

2. 连接到 MongoDB 并查询数据

const mongoskin = require('mongoskin');
const db = mongoskin.db('mongodb://localhost:27017/mydatabase?auto_reconnect');

// 假设你的集合名为 'treeNodes'
const collection = db.collection('treeNodes');

3. 递归函数获取树形结构数据

function getTreeData(nodeId) {
    return new Promise((resolve, reject) => {
        collection.findOne({ _id: mongoskin.helper.toObjectID(nodeId) }, (err, node) => {
            if (err) return reject(err);
            if (!node) return resolve([]);

            // 递归获取子节点
            const getChildNodes = async (childrenIds) => {
                const childrenPromises = childrenIds.map(getTreeData);
                const children = await Promise.all(childrenPromises);
                return children.flat();
            };

            // 获取当前节点的子节点
            getChildNodes(node.children || []).then(children => {
                node.children = children;
                resolve(node);
            });
        });
    });
}

4. 主程序逻辑

async function main() {
    try {
        const rootNode = await getTreeData('yourRootNodeId'); // 替换为你的根节点 ID
        console.log(JSON.stringify(rootNode, null, 2));
    } catch (error) {
        console.error("Error:", error);
    }
}

main();

解释

  • getTreeData 函数:接受一个节点 ID,查询该节点及其所有子节点。它使用递归来处理子节点。
  • getChildNodes 函数:用于递归获取所有子节点,并将它们合并到一个数组中。
  • main 函数:调用 getTreeData 函数来获取根节点及其所有子节点,并打印出结果。

这样,你可以轻松地将树形结构的数据从 MongoDB 中提取出来,并以 JSON 格式输出。希望这对你有所帮助!


当然可以!以下是如何使用Node.js、MongoDB和Mongoskin来获取树形结构的数据,并将其转换为JSON格式的示例。

示例代码

首先确保安装了mongoskin包:

npm install mongoskin

然后,编写如下代码:

const mongoskin = require('mongoskin');
const db = mongoskin.db('mongodb://localhost:27017/mydb?auto_reconnect');

function getTree() {
    return new Promise((resolve, reject) => {
        db.collection('nodes').find().toArray((err, docs) => {
            if (err) return reject(err);
            const tree = buildTree(docs);
            resolve(tree);
        });
    });
}

function buildTree(nodes, parentId = null) {
    const children = nodes.filter(node => node.parentId === parentId);
    for (const child of children) {
        child.children = buildTree(nodes, child._id);
    }
    return children;
}

getTree()
    .then(tree => console.log(JSON.stringify(tree, null, 2)))
    .catch(err => console.error('Error fetching tree:', err));

解释

  1. 引入Mongoskin:

    const mongoskin = require('mongoskin');
    
  2. 连接到MongoDB数据库:

    const db = mongoskin.db('mongodb://localhost:27017/mydb?auto_reconnect');
    
  3. 获取所有节点:

    function getTree() {
        return new Promise((resolve, reject) => {
            db.collection('nodes').find().toArray((err, docs) => {
                if (err) return reject(err);
                const tree = buildTree(docs);
                resolve(tree);
            });
        });
    }
    
  4. 构建树形结构:

    function buildTree(nodes, parentId = null) {
        const children = nodes.filter(node => node.parentId === parentId);
        for (const child of children) {
            child.children = buildTree(nodes, child._id);
        }
        return children;
    }
    
  5. 输出结果:

    getTree()
        .then(tree => console.log(JSON.stringify(tree, null, 2)))
        .catch(err => console.error('Error fetching tree:', err));
    

数据库模型

假设你的nodes集合中的文档具有以下结构:

{
    "_id": ObjectId,
    "name": "Node Name",
    "parentId": ObjectId | null
}

以上代码会从MongoDB中读取所有的节点,根据parentId构建树形结构,并最终打印出JSON格式的树。

回到顶部