I wrote a query:
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray();
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> }
.
How can I return array of found documents instead of this string?
toArray: Link to the documentation
The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.
A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap.
The MongoDB Async driver provides an asynchronous API that can leverage either Netty or Java 7's AsynchronousSocketChannel for fast and non-blocking IO.
You are getting this error because the find() method is asynchronous, that's why the promise is pending: it is still fetching.
db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray().then((data) => {
// Here you can do something with your data
doSomethingWithTheResult(result)
})
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
async function getResults() {
return db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray();
}
const results = await getResults();
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!
In the toArray()
method you write a callback function:
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray(function(err, result) {
if (results.length > 0) {
console.log(results);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With