添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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!

The return type of find() is defined as a Cursor: mongodb.github.io/node-mongodb-native/3.1/api/… whereas the return type of Cursor.toArray is a Promise: mongodb.github.io/node-mongodb-native/3.1/api/…. Is it possible to just do this: var result = await db.collection('diseases').find(query).toArray(); and add the async keyword to the enclosing function? – user1063287 Nov 13, 2018 at 17:13 I never used it like that, but if to Array() returns a promise you can await on it just like you said – Denis Nov 13, 2018 at 17:22 @Denis I stumbled across this answer looking for a solution to the same problem, but I would like some clarification if you wouldn't mind providing. Why to we need to do .toArray().then(...) for the find() function, but for the findAndModify() function, we can use doc.value right in the callback. Is findAndModify() not asynchronous? – Tara Nov 13, 2019 at 21:23 It's a bit late, but I hope I can still help. Since you pass a callback to the findAndModify() it will internally wait for the find to finish and then run your callback, that's why you can acess it directly. It doesn't mean the method itself is synchronous (that's why you need a callback) it just means that the method will run your callback at the right moment – Denis Dec 13, 2019 at 17:51

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);
                For some reason when I try to use the callback function within toArray it never fires. If I use the answer after yours it works fine.
– FrankT
                Feb 8 at 18:06

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.