I have my own class and method call findByIdDate() When I find the data then inside of db.collection() I will get result but if I want to return that data from my own method it will come back undefined. Could someone provide me example how to get the data please? I have been searching but I can not find any answers to this problem. I'm new to node and express My Method
findByIdDate(){
let data = this.db.collection('journal').find({date: this.Date}).toArray((err, result) => {
if(err){return console.log(err)}
console.log(result) // I have data
return result
})
return data
}
in my other file I use it like this
app.post('/id', (req, res) => {
const DIARY = new diary('new', '16 January 2020', db)
let result = DIARY.findByIdDate()
console.log(result) // undefined
});
toArrayis executed asynchrously and that nothing is returned fromtoArray()? I'm not familiar with the JS MongoDB API, but async calls are not unheard of in the JS world.resultbefore it has been returned byfindByIdDate(). There's a couple ways to handle this, the most modern being the use ofasync/await. This should lead you in the right direction.