Search code examples
node.jsmongodbdatabase-cursor

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


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


Solution

  • 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!