Hacen Selahy
Hacen Selahy

Reputation: 79

Can't set a variable inside mongoose callback function

I can't understand why "productsAvailable" show true after being set to false.

router.post('/api/transactions', (req, res) => {
    var productsAvailable = true

    for(var i=0; i<3; i++) {
        ProductM.findOne({name:"not available name"}).exec((err, product) => {
            productsAvailable=false //set to false 
        })

        console.log(productsAvailable) //this show true
    }
})

Thanks you

Upvotes: 0

Views: 38

Answers (1)

Sergii Vorobei
Sergii Vorobei

Reputation: 1487

This is async function, please log inside of it:

ProductM.findOne({name:"not available name"}).exec((err, product) => {
    productsAvailable=false
    console.log(productsAvailable)
    // you probably need to send response here
})

Upvotes: 1

Related Questions