awariat
awariat

Reputation: 382

Firestore batch update - check if doc exists

I try to update documents using batch. It is OK if they exists but if not I have error. I would like to "set" if doc does not exists

var batch = db.batch();

            $.each(newProductsArray, function (key, value) {
                if (value['sku']) {
                    console.log(value['sku']);
                    var sku = value['sku'];
                    var name = value['name']
                    docRef = db_user.collection("products").doc(sku);

                    batch.update(docRef, {
                        productSKU: sku + "sku",
                        productName: name

                    });

                }

            });

            // Commit the batch
            batch.commit().then(function () {
                ...
                )
            });

Upvotes: 0

Views: 722

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317750

It sounds like you want to use set() instead of update(), telling it to merge fields if the document already exists.

batch.set(docRef, { ... }, { merge: true });

Upvotes: 3

Related Questions