MongoDB: cursor.toArray returns Promise {

2019-07-17 02:34发布

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

3条回答
Melony?
2楼-- · 2019-07-17 02:53

You are getting this error because the find() method is asynchronous, that's why the promise is pending: it is still fetching.

var results = db.collection('diseases').find({
  'ttl.txt': {
    $regex: data,
    $options: 'i'
  }
}).then((data) => {
    // Here you can do something with your data
    result = data.toArray()
    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() {
    db.collection('diseases').find({
        'ttl.txt': {
        $regex: data,
        $options: 'i'
        }
    })
}

var results = await getResults();
results = results.toArray()

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!

查看更多
乱世女痞
3楼-- · 2019-07-17 02:53

The error is giving because it's a promise

var results = db.collection('diseases').find({
    'ttl.txt': {
            $regex: data,
            $options: 'i'
    }
}).lean().then(function (obj) {
    if (!obj) {
            return resolve('not find');
    }

    return resolve(obj);
}).catch(function (err) {


    return reject(err);
});
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-07-17 02:57

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);
     }
});
查看更多
登录 后发表回答