【问题标题】:the 'findIndex' is undefined in nodejs'findIndex' 在 nodejs 中未定义
【发布时间】:2021-04-30 00:54:05
【问题描述】:

在 nodejs 中,findIndex 是未定义的

let userCart = db.get().collection(collection.CART_COLLECTION).findOne({user:objectId(userId)})
            if (userCart){
                let proExist=userCart.products.findIndex(product=> product.item==proId)
                console.log(proExist);
            }

在我的控制台中显示:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'findIndex' of undefined
at C:\Users\Toshiba\Desktop\Projects\E-Commerce Application\helpers\user-helper.js:49:48
at new Promise (<anonymous>)
at Object.addToCart (C:\Users\Toshiba\Desktop\Projects\E-Commerce Application\helpers\user-helper.js:46:16)

【问题讨论】:

  • 那是因为userCart.products未定义,请确保它是一个数组。
  • 这是因为 userCart 没有任何 products 键!
  • "findIndex 未定义" 这不是错误所说的。它告诉您它无法读取findIndex 来自 undefined。无论它试图在findIndex 上执行什么,都是undefined
  • 我的猜测是第一行将 Promise 分配给userCart,而不是购物车对象。您可能需要await db 命令。

标签: javascript


【解决方案1】:

因为 Mongoose DB 操作是promises。而您只是想在promise 完成之前将userCart 阅读为object。 您应该使用await 关键字等待findOne() 返回结果。

(Recommended) Using mongoose promises with async/await

async function something(){
   let userCart = await db.get().collection(collection.CART_COLLECTION).findOne({user:objectId(userId)});
   if (userCart){
        let proExist=userCart.products.findIndex(product=> product.item==proId)
        console.log(proExist);
   }
}

【讨论】:

    【解决方案2】:

    错误

    无法读取未定义的属性“findIndex”

    来自你的这行代码:

    userCart.products.findIndex

    这意味着您的 userCart 对象不包含属性 products

    您能否尝试使用Promise 语句从数据库中获取数据?在解析块中,您可以添加您的逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多