【问题标题】:Node.js MongoDB collection.find().toArray returns nothing [duplicate]Node.js MongoDB collection.find().toArray 不返回任何内容[重复]
【发布时间】:2017-07-15 13:51:20
【问题描述】:

虽然我发现了与我类似的问题,但我无法自己解决问题。

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

这是我的代码:

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”,但没有结果。

【问题讨论】:

  • 从 MongoDB 的文档来看,你不能将参数传递给 toArray 为什么不干脆做test = database.customers.find().toArray()
  • @Ozan 仍未定义
  • @Petar D. 我刚刚在本地开发中进行了测试,它确实返回了所有文件。我不确定是什么原因造成的。你为什么不使用猫鼬?
  • @Ozan 我很快就会开始使用 Mongoose,但首先我想学习基础知识
  • 你可以试试这个,var mongoDatabase = require('../db'); var 数据库 = mongoDatabase.getDb(); function find() { return database.collection("customers").find().toArray(); } module.exports = { 查找 };

标签: javascript node.js mongodb


【解决方案1】:

最好的方法是使用 Promise。这样做。

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)
    })
  })
}

【讨论】:

  • 我应该包括哪些模块?那是'jQuery'吗?
  • 不,我已经编辑过了,你应该安装一个 npm 模块 'q'
  • 没有必要添加另一个模块,因为 Node.js 从 0.12 版本开始就支持原生 Promises。
  • 感谢您指出这一点。我已经编辑了我的答案。
  • @PetarD。如果不想包含模块也可以使用上面的代码
猜你喜欢
  • 1970-01-01
  • 2016-08-10
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多