Click here to Skip to main content
15,446,232 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to build a dynamic menu in nodejs with mongoose, but my method is not working. i get a list of menu items with an empty coreMongooseArray as its children property [{model.children = coreMongooseArray(0)}, {model.children = coreMongooseArray(0)}]



, but i should be getting a list of menu items each with their own list of children menu items. [{model.children = [model]}, {model.children = [model, model], {model.children = null}]

below is my method, route and form schema data. someone help!

Route
router.get('/scripts/menu', async function(req, res, next) {
    console.log('menutree is working');
    var initial = await Menu.find().populate('parent');
    var menutree = await Menu.GetMenuTree(initial, null, '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(unfilteredlist, parent = undefined, category) {

    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(unfilteredlist, item._id, item.category);
        return item

    })

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

});


What I have tried:

i have tried to alter my method to get it to work, but i dont know whats wrong, im now trying to find someone who can offer some guidance online
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900