Dynamic menu with mongoose method

54 views
Skip to first unread message

alym karim

unread,
Feb 1, 2020, 10:15:20 AM2/1/20
to Mongoose Node.JS ODM

Hi,


I’m trying to build a dynamic menu which is built using data in database. i have a mongoose method that should get me a list of menu items with each of their children as a property on the object, however when i call my code i get an empty list of children. please see the method below and let me know whats wrong.


When I use fetch to get the route data from the front-end i get an array of models. But all of models.children properties are empty coreMongooseArrays.

this should not be the case, the first model in the array should be populated with three children objects based of the data in the database.


Can anyone help me figure out what is wrong with my method and what i need to change to get the children inside the parents array



Route


router.get('/scripts/menu'async function(reqresnext) {
    console.log('menutree is working');
    var initial = await Menu.find().populate('parent');
    var menutree = await Menu.GetMenuTree(initialnull'5dfe0009551b160edcdc89ce');
    await res.status(200).send(menutree)
})


Schema


const menuSchema = new Mongoose.Schema({
    title: {
        type: String,
        trim: true,
        required: true
    },
    parent: {
        type: Mongoose.Schema.Types.ObjectId,
        ref: 'Menu'
    },
    active: {
        type: Boolean,
    },
    page: {
        type: String,
        trim: true
    },
    category: {
        type: Mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required: true
    },
    children: [Mongoose.Schema.Types.Mixed]

}, {
    timestamps: true
})


Method


menuSchema.static('GetMenuTree'async function(unfilteredlistparent = undefinedcategory) {

    var MenuObj = this;

    var filteredlist = unfilteredlist.filter(function(item) {
        return item.parent == parent && item.category == category;
    })


    filteredlist = filteredlist.map(async function(item) {

        item.children = await MenuObj.GetMenuTree(unfilteredlistitem._iditem.category);
        return item

    })

    return Promise.all(filteredlist).then(function(results) {
        return results
    })

});



Reply all
Reply to author
Forward
0 new messages