【问题标题】:Node + Mongo : findOne OK but find().forEach DONTNode + Mongodb:findOne 可以,但 find().forEach 不行
【发布时间】:2017-09-01 17:43:47
【问题描述】:

我的问题似乎与节点的异步方面有关,但我不明白为什么。

此代码有效:

      expertsArray = ["expert1", "expert2"];
      db.collection("users").findOne({first_name: expertsArray[0]}, function(err, expert) {
        console.log(expert.userid);
        });
      }); 

这段代码有BUGS:

      expertsArray = ["expert1", "expert2"];
      db.collection("users").find({ first_name: {$in: expertsArray} }, function(err, experts) {
        experts.forEach(function(err, expert) {
          console.log(expert.userid);
          });
        });
      }); 

第二种情况,experts存在并且是一个[Object object],但是错误是:

错误:[致命]您的机器人类型错误中发生未处理的异常: 无法读取 null 的属性“用户 ID”

我也尝试将第一个代码放入 FOR 循环,但出现了相同的错误... 任何人都可以帮助我理解吗?非常感谢:)

【问题讨论】:

  • 怎么可能同时是object和null……也许是薛定谔的变量。
  • 抱歉打错了:专家存在,但专家不存在

标签: node.js mongodb typeerror


【解决方案1】:

forEach中的参数有误。

根据Mozilla,参数为:

currentValue, index

但你有

err, expert

所以试试吧:

experts.forEach(function(expert, expertIndex) {
  console.log(expert.userid);
  });
});

【讨论】:

  • 你是最棒的! ;) 非常感谢您
  • 我应该和 each() 函数混淆了:cursor.each(function(err, item) {
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 2020-11-15
  • 2020-08-29
  • 2014-12-03
相关资源
最近更新 更多