I am not much experienced with async/await, but I have incorporated the keywords in a function which basically fetch or POST data to MongoDB database. It seems like await does not wait for the promise to be fulfilled and returns an undefined response object.
I am getting the following error:
res.error(404).json({message: e.message}) ^
TypeError: Cannot read properties of undefined (reading 'error') at Object.getAllItems (/Users/myName/Desktop/TODOList/backend/Controllers/ItemsConroller.js:12:13)
Here is my code:
ItemsController.js:
const getAllItems = async (req, res) => {
try{
const items = await Item.find({})
res.status(200).json(items)
}
catch(e){
res.error(404).json({message: e.message})
}
}
Server.js file:
app.get('/todos', (req, res) => {
dbItem.getAllItems().then(data => {
console.log("entered")
res.send(data);
})
})
Same problem with other functions in the controller file which incorporates await/async keywords.
Thanks.
CodePudding user response:
You are not passing your req and res object to your /todos endpoint:
To make you app more robust try this:
You can use getAllItems as your middleware like this
app.get('/todos', dbItem.getAllItems, (req, res) => {
if(!req.error){
res.send(req.items)
}else{
res.send(req.error)
}
})
And attach your variables to the req object and pass them to /todos
const getAllItems = async (req, res, next) => {
try{
const items = await Item.find({})
req.items = items
next()
}
catch(e){
req.error = e.message
next()
}
}
