Node.js MongoDB collection.find().toArray不返回任何内容 [英] Node.js MongoDB collection.find().toArray returns nothing

查看:114
本文介绍了Node.js MongoDB collection.find().toArray不返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我发现了与我类似的问题,但我无法独自解决问题.

Although I found similar questions to mine, I couldn't solve the problem on my own.

在我的'../models/user'模型中,我想找到所有用户并将其放入数组,然后将该数组返回给控制器(我将在其中使用信息).

In my '../models/user' model I want to find all users and put them into array, and return that array to the controller(where I will use the info).

这是我的代码:

var mongoDatabase = require('../db');
var database = mongoDatabase.getDb();

function find() {
    var test;
    database.collection("customers").find().toArray( function(err, docs) {
        if(err) throw err;
        console.log(docs); //works fine
         //I'd like to return docs array to the caller
        test = docs;
    });

    console.log(test); //test is undefined  
}

module.exports = {
    find
};

我还注意到,"console.log(test)"位于"console.log(docs)"之前.我尝试将'docs'参数作为函数参数传递给'find',但是没有结果.

I also noticed, that 'console.log(test)' goes before 'console.log(docs)'. I tried passing 'docs' argument as function parameter to 'find', but without result.

推荐答案

最好的方法是使用Promises.这样做吧.

The best way is to use Promises. Do it like this.

function getUsers () {
  return new Promise(function(resolve, reject) {
     database.collection("customers").find().toArray( function(err, docs) {
      if (err) {
        // Reject the Promise with an error
        return reject(err)
      }

      // Resolve (or fulfill) the promise with data
      return resolve(docs)
    })
  })
}

这篇关于Node.js MongoDB collection.find().toArray不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆