-1

I have a variable called itemExist and set that equal to false. My goal is to set this variable's value to true if a condition happens. My code is this:

var itemExist = false;

        user.findById({_id: decoded._id}).populate('shoppingCart').exec((err, items)=>{
            items.shoppingCart.forEach(async item=>{
                if(item.productId == productId){
                    itemExist = true;

When I console log the itemExist variable outside of all theese functions

console.log(itemExist);

I get that result on the console:

false

But it should be true. How can I solve this problem, what is causing that?

Güney
  • 91
  • 2
  • 9

1 Answers1

0

Perform your work inside exec function

user.findById({_id: decoded._id}).populate('shoppingCart').exec((err, items)=> 
    {
        const itemInArr = items.shoppingCart.find(item => item.productId === productId);
        //!! - convertation to boolead value
        itemExist = !!itemInArr;
        console.log(itemExist);
    }
);
Pasha
  • 621
  • 8
  • 21