sequelize-nested-set - Create root record

By xngo on September 4, 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 root record.
sequelize.sync()
    .then(() => {
 
        (async () => {
            let root = new Tree();
            root.label = 'Root record';
            root = await Tree.createRoot(root);
 
            let childNode = new Tree();
            childNode.label = 'child node';
            await root.addChild(childNode);
        })();
 
    });

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.