0

I have the following function that tries to read a value in an inventory database and increment it...

app.post('/UpdateInventory', FBAuth,(req,res) => {

    const firestore =  admin.firestore;

    let InventoryRef = admin.firestore().collection('Inventory');

    let GetID = InventoryRef.where('IngredientID', '==','BA001').get()
    .then(snapshot => {
        if (snapshot.empty) {
            console.log('No matching documents');
            return;
        }

        snapshot.forEach(doc => {
            var CatchDoc = doc.id;

            console.log(doc.id, '=>', doc.data());
        });
    })

    admin
        .firestore()
        .collection('Inventory')
        .doc(CatchDoc)
        .update({   
            IngredientAvailability: firestore.FieldValue.increment(10)
        });

    res.json({CatchDoc});

});

I have set up a variable called "CatchDoc" that is supposedly cathcing the document id that complies with the condition im putting.

The problem is that I always get the following error:

ReferenceError: CatchDoc is not defined

Even though that the console.log output is:

Hm4a9VwDVv1QsYgzKBdl => { IngredientAvailability: 220,
>    IngredientImage: 'image.jpg',
>    IngredientID: 'BA001',
>    IngredientPortion: 30 }

(when i hardcode the Document ID in the .doc reference)

The "Hm4a9....." string is the doc ID I want to save in the CatchDoc variable but I can't...

Can you shed some light ? I have used already the "set" and "let" declaration, they doesnt work neither...thanks a lot ¡

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Your variable `CatchDoc` is scoped to be visible only within the callback function that you passed to `forEach`. It is not visible anywhere else in your code. Another problem is that it gets recreated and redefined every iteration through the loop. So it's not clear what value you expect it to have by the time it reaches the last line of code, so it's not really clear to us what exactly you intend to send. – Doug Stevenson May 31 '20 at 19:12
  • @DougStevenson Well the end product is basically increment the field "IngredientAvailability" of the document that satisfies the condition of having the "IngredientID" field == BA0001 (This will be later a function in which BA001 will be a variable). But now that you say the "for each doc" iterates thru all the docs, not only the ones that fulfill the condition, right ? So I need to add another conditional so I confirm the CatchDoc variable will have the Doc ID value, right ? Edit: It didnt worked – Juan Acosta May 31 '20 at 19:20

0 Answers0