【问题标题】:mongoose find returned undefined document猫鼬找到返回的未定义文档
【发布时间】:2023-03-06 05:24:01
【问题描述】:

我有一些看起来像这样的代码。从字面上看,只是表面上的变化 从我的实际代码中删除和删除:

Entry.find(conditions)
.select('ymd intentions outcomes goalCounts')
.lean()
.exec()
.then(function (entries) {
  if (!entries.length) {
    res.write(']')
    res.end()
  }
  entries[entries.length-1].isLast = true
  // more processing of entries etc
}, function (err) {
  // do something with error
})

它通常可以工作,但我的生产服务器刚刚报告了一个错误:isLast=true 行失败

TypeError: Cannot set property 'isLast' of undefined

因为那里有一个检查来确保数组本身不为空,所以我知道传递给这个函数的是一个非空数组,它的最后一项本身是未定义的。 ymd 是必填字段,因此不应有任何结果为 {}

这是在任何情况下的预期行为(与lean() 有关吗?)还是代表某种 mongo 错误?

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query


    【解决方案1】:

    您的代码在您提及 if 检查后继续,因此如果 entries 的长度为 0,您将收到您所看到的错误。

    res.end() 调用之后返回以太币,或者将引发错误的行放在else 子句中:

    if (!entries.length) {
      res.write(']')
      res.end()
      return;
    }
    entries[entries.length-1].isLast = true
    

    if (!entries.length) {
      res.write(']')
      res.end()
    } else {
      entries[entries.length-1].isLast = true
    }
    

    【讨论】:

    • 哈。当然。看到“res.end()”让我觉得它已经完成了。呸!我比这更清楚。
    猜你喜欢
    • 2015-01-06
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2019-05-19
    相关资源
    最近更新 更多