0

I have no idea why exported function findChilds return undefined

Function look like this:

const Folder = module.exports = mongoose.model('folder', FolderSchema);

module.exports = {

    findChilds: (folderId) => {
        Folder.find({
            parent: folderId
        }).then((childs => {
            childs.forEach((child => {
                module.exports.findChilds(child._id)
            }));
            return childs;
        }));
    }

};

And calling:

const folderModel = require('../models/Folder');

router.get('/remove/:id', (req, res) => {
    let functionResult=folderModel.findChilds(req.params.id);
    console.log(functionResult)
});

functionResult show only undefined.

Marcin
  • 243
  • 3
  • 20

1 Answers1

0

When using arrow functions, you have 2 ways of returning a value:

Using a single expression without brackets {}:

module.exports = {
    findChilds: (folderId) => Folder.find({ parent: folderId})
       .then((childs => {
            childs.forEach((child => {
               module.exports.findChilds(child._id)
            }));
            return childs;
        }))
}

Using the actual return keyword:

module.exports = {
    findChilds: (folderId) => {
        return Folder.find({parent: folderId }).then((childs => {
            childs.forEach((child => {
                module.exports.findChilds(child._id)
            }));
            return childs;
        }));
    }
};

Keep this in mind when looking at the forEach loops inside your then method, you'll have problems there as well!

Also english is not my native language, but childs sounds better as children ;)

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
  • There are hundreds of dups of this question. It's better to point to the best answer of one of those rather than continue to add to the hoard of duplicate answers. – jfriend00 Nov 05 '17 at 19:22