1

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 
});
asked Jan 17, 2020 at 14:33
2
  • Can you extract and provide a minimal reproducible example please? Also, just wondering, could it be that the closure you give to toArray is executed asynchrously and that nothing is returned from toArray()? I'm not familiar with the JS MongoDB API, but async calls are not unheard of in the JS world. Commented Jan 17, 2020 at 14:42
  • 1
    You're probably console.logging result before it has been returned by findByIdDate(). There's a couple ways to handle this, the most modern being the use of async/await. This should lead you in the right direction. Commented Jan 17, 2020 at 14:48

1 Answer 1

2

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

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.