MongoDB: cursor.toArray returns Promise { <pending> }

Viewed 13294

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

4 Answers

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)
    }
}
Related