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
});
1 Answer 1
It would be best to do away with callback functions and make the function async/await
as:
async findByIdDate(){
try {
let data = await this.db.collection('journal')
.find({date: this.Date})
.toArray() // returns a promise which can be 'awaited'
console.log(data)
return data
} catch (err) {
console.error(err)
throw err
}
}
And use it in your route as
app.post('/id', async (req, res) => {
try {
const DIARY = new diary('new', '16 January 2020', db)
let result = await DIARY.findByIdDate()
console.log(result)
} catch(err) {
console.error(err)
}
})
answered Jan 17, 2020 at 14:48
1 Comment
wlh
is absolutely correct. Let me add: The reasoning is that the call to MongoDB is asynchronous. And the return statement in your original code outside of the
find
call was being called synchronously. It returned data as undefined
because at the time it was called, data was still undefined
. The previous statement had yet to return anything.lang-js
toArray
is 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.result
before 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.