【问题标题】:Node.js Cannot read property 'toJsonWith' of undefinedNode.js 无法读取未定义的属性“toJsonWith”
【发布时间】:2021-12-05 08:30:39
【问题描述】:

我正在尝试返回图标,结果是在页面上生成它们

下面map下面的代码是我试图返回页面的所有结果。

const icons = await Icon.find({ _id: { $in: ids } }).select({ ...options.select, ...options.additional })
    const results = ids
      .map(id => {
        const iconsGroup = icons.find(icon => icon.id === id)
        if (query.hasPublishingError) {
          iconsGroup.icons = iconsGroup.icons.filter(el => (el.errorsData.length > 0 && el.status === 'draft'))
        }
        return iconsGroup
      })
      .map(i => i.toJsonWith(options.select))

await postProcess(results)

    return {
      docs: results,
      limit: response.limit,
      page: response.page,
      pages: response.pages,
      total: response.total
    }

当我发出GET 请求时,我收到如下错误:

TypeError: Cannot read property 'toJsonWith' of undefined\n

痛点是.map(i => i.toJsonWith(options.select))

顺便说一句,由于某种原因,这个函数toJsonWith 无法在某处作为声明找到。 请帮帮我,我试图弄清楚这里出了什么问题 4 天。

【问题讨论】:

  • cannot read property 'toJsonWith' of undefined 意味着在这种情况下i 是未定义的,所以可能在映射之前检查结果是否为空
  • 函数toJsonWith是你自己写的吗?如果不是你可能忘记导入它,但我没有找到任何包含这个功能的包
  • @mrJQuery linter 告诉我可以从某个对象调用toJsonWith(),我认为不需要导入它。是的,i 很可能是未定义的,但我不明白如何重新评估此表达式以使其正常工作,同样如果 i 未定义,为什么字段 idnot undefined
  • i 未定义,因为您的第一张地图不返回任何内容。 if 会检查 icons.find(icon => icon.id === id) 是否返回任何东西。

标签: javascript node.js typescript dictionary nestjs


【解决方案1】:

_id 应该始终是唯一的,所以

const iconsGroup = icons.find(icon => icon.id === id)

应该返回一个最多包含一个元素的arrayObject。

然后你检查发布错误

if (query.hasPublishingError) {
      iconsGroup.icons = iconsGroup.icons.filter(el => (el.errorsData.length > 0 && el.status === 'draft'))
    }

这里可能会发生iconsGroup是一个空数组。

接下来您制作第二张地图以使用您的神奇 toJsonWith(我也不知道它的作用)。

您可以组合这两个地图并直接迭代您的图标,而不是在您的 id 上使用地图(以下代码根据 query.hasPublishingError 为您提供一组图标):

const results = icons.map(icon => {
if (query.hasPublishingError && icon.errorsData.length > 0 && icon.status === 'draft') {
    return icon.toJsonWith(options.select)
} else {
    return icon.toJsonWith(options.select)
}
})

【讨论】:

  • toJsonWith 是我之前写的一个函数,我必须使用它。我会尝试这个并标记答案以防万一
猜你喜欢
  • 2016-05-09
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 2021-11-24
  • 2020-04-17
相关资源
最近更新 更多