Hello, I am trying to use Aggregate pipeline in a node.js router
The aggregation gives me the perfect result in MongoDB Compass:
_id:61b1da8abab5f8eefe9e1589
sublinkid:2
sublinkicon:"fas fa-building"
sublinkname:"NewCo"
sublinkurl:"newco"
I then exported the pipeline to node and created function:
const db = require('../config/keys')
const getMenuItem = async () => {
const pipeline = [
{
'$unwind': {
'path': '$sublinks'
}
}, {
'$match': {
'$and': [
{
'menuitemname': 'Dashboard'
}, {
'sublinks.sublinkid': 1
}
]
}
}, {
'$project': {
'_id':0,
'menuitemname': '$menuitemname',
'menuitemicon': '$menuitemicon',
'sublinkid': '$sublinks.sublinkid',
'sublinkicon': '$sublinks.sublinkicon',
'sublinkname': '$sublinks.sublinkname',
'sublinkurl': '$sublinks.sublinkurl'
}
}
]
const result = db.collection("adminnavbar").aggregate(pipeline);
result.next(function(err, res) {
console.log(res)
})
}
module.exports = getMenuItem
then I created a router.get:
router.get('/updatemenuitem/:id', (req, res) => {
const menudetail = getMenuItem()
console.log(menudetail)
})
although I call the function first, the console.log in the router gives an error and afterwards the console.log from the function returns the result. Could anyone help, the console log in the router should give the result of the function… thank you very much (I only started working with MongoDB 8 weeks ago, VERY happy with it!)