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.
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)
})
**Method**
menuSchema.static(‘GetMenuTree’, async function(unfilteredlist, parent = undefined, category) {
var MenuObj = this;
var filteredlist = unfilteredlist.filter(function(item) {
return item.parent == parent
})
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
})
});
**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
})