Situation
I wrote a query:
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray();
Problem
Then I printed results
to a console.
if (results.length > 0) {
console.log(results);
}
ToArray method must return array of found documents. But this method returns me this string: Promise { <pending> }
.
Question
How can I return array of found documents instead of this string?
PS
toArray: Link to the documentation
You are getting this error because the find() method is asynchronous, that's why the promise is pending: it is still fetching.
Notice that you have your data inside a callback. For more info about promises check Promise
Depending on your node version (7.6+ I believe), you can use something like this
So your code with look like a synchronous code. The key here is the async/await command that wait for the promise results.
Hope it helps!
The error is giving because it's a promise
In the
toArray()
method you write a callback function: