1

In nodejs the findIndex is undefined

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

in my console it says:

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)
  • that's because `userCart.products` is undefined, please make sure it is an array. – wangdev87 Jan 26 '21 at 08:26
  • this is because **userCart** do not have any **products** key ! – Zulqarnain Jalil Jan 26 '21 at 08:28
  • 1
    "_the findIndex is undefined_" That is not what the error says. It tell you that it cannot read `findIndex` _from_ `undefined`. Whatever it tries to perform `findIndex` on is `undefined`. – Ivar Jan 26 '21 at 08:30
  • My guess is that the first line assigns a Promise to `userCart`, not a cart object. You probably need to `await` the db command. –  Jan 26 '21 at 08:35

2 Answers2

2

The error

Cannot read property 'findIndex' of undefined

is coming from this line of your code:

userCart.products.findIndex

which means that your userCart object doesn't contain a property products.

Can you please try using Promise for the statement to get the data from DB? And in the resolve block, you can add your logic.

1

Because Mongoose DB operations are promises. And you are just trying to read userCart as an object before the promise getting finished. You should use await keyword to wait until the findOne() returns the result.

(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);
   }
}
BadPiggie
  • 5,471
  • 1
  • 14
  • 28