Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
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.
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);
–
A modern approach using async/await.
In this case, we want to get matching bird colors in the birds collection.
async function getBirdsByColor(color) {
try {
var birds = await db.collection('birds').find({
color: color
}).toArray()
if(!birds || !birds.length) {
throw('No birds with color: ' + color)
console.log('Successfully found one or more birds:', birds)
} catch (e) {
console.log('Bird search failure: ', e)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.