Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 849
Max Mikhalchuk Avatar asked Jul 19 '17 18:07

Max Mikhalchuk


People also ask

What is toArray in MongoDB?

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.

What is a Promise in MongoDB?

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.

Is MongoDB asynchronous?

The MongoDB Async driver provides an asynchronous API that can leverage either Netty or Java 7's AsynchronousSocketChannel for fast and non-blocking IO.


2 Answers

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!

like image 91
Denis Avatar answered Oct 21 '22 20:10

Denis


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);
     }
});
like image 40
Achilles Ram Nakirekanti Avatar answered Oct 21 '22 20:10

Achilles Ram Nakirekanti