sequelize-nested-set - Display tree

By xngo on September 5, 2022

const { Sequelize, DataTypes, BulkRecordError } = require('sequelize');
const ns = require('sequelize-nested-set');
 
// Connect to database.
const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'treeorg.sqlite'
});
 
// Define Tree model.
const Tree = ns(sequelize
                , DataTypes
                , 'Tree'
                , { label: DataTypes.STRING }
                , { //tableName: 'Tree'
                    timestamps: false
                    , hasManyRoots: true
                    , levelColumnName: 'level'
                }
);
 
// Create tree.
// Note: Call reload() before addChild() to update variable with a parent node.
//      Otherwise, parentId is not returning correctly.
//      https://github.com/fremail/sequelize-nested-set/issues/32
sequelize.sync()
    .then(() => {
 
        (async () => {
 
            let electronics = new Tree(); electronics.label = 'Electronics';
            electronics = await Tree.createRoot(electronics);
 
            let phones = new Tree(); phones.label = 'Phones';
            await electronics.reload();
            await electronics.addChild(phones);
 
                let xiaomi = new Tree(); xiaomi.label = 'Xiaomi';
                await phones.reload();
                await phones.addChild(xiaomi);
 
            let TVs = new Tree(); TVs.label = 'TVs';
            await electronics.reload();
            await electronics.addChild(TVs);
 
                let samsung = new Tree(); samsung.label = 'Samsung';
                await TVs.reload();
                await TVs.addChild(samsung);
 
                let apple = new Tree(); apple.label = 'Apple';
                await TVs.reload();
                await TVs.addChild(apple);
 
 
            // ----------------------------------------
            // Display tree.
            const printTree = async function (ns) {
                const items = await Tree.fetchTree(10);
                let strings = [];
                for (let item of items) {
                    // console.log(item)
                    let parent = await item.getParent();
                    strings.push(("- ".repeat(item.level) + `${item.label} [id ${item.id}, parentId ` + (parent.id || '-') + `]`));
                }
                console.log(strings.join("\n"));
            }
            printTree(electronics);
 
        })();
 
    });
Electronics [id 1, parentId -]
- Phones [id 2, parentId 1]
- - Xiaomi [id 3, parentId 2]
- TVs [id 4, parentId 1]
- - Samsung [id 5, parentId 4]
- - Apple [id 6, parentId 4]

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.