'Sequelize, lazy loading on associated models

I am using sequelize 6.17

I have a class Folders which has many childFolders and files.

I would like to lazy load the childFolders and files that are on the association.

const folderContent = await db.folders.findAll({
            where: {
               parentFolderId: 123
            },
            limit,
            offset,
            include: [
               {
                  model: db.folders,
                  as: "childFolders",
                  required: false
               },
               {
                  model: db.files,
                  as: "files",
                  required: false
               }
            ],
         });

This will not work and will return folderContent.files and folderContent.childFolders.

Would be possible to get x amount of childFolders and when there is not anymore childFolders to start getting the files? Can this be returned as an array of childFolders and files?



Solution 1:[1]

By indicating include option you perform eager loading and you will get all-in-one. If you wish to get childFolders or files separately for a certain folder model instance you need to call special methods getChildFolders or getFiles (generated by Sequelize):

const folderContent = await db.folders.findAll({
            where: {
               parentFolderId: 123
            },
            limit,
            offset,
         });

for (const folder of folders) {
  const files = await folder.getFiles();
  const childFolders = await folder.getChildFolders();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anatoly