I'm trying to update PITA denormalised db structure. I know there are already answers on how to check if document exist on get even documentation is pretty clear about it but I just cannot find anything what would check if document exist on update "set" and "where".
First I want to check one document if exist before updating
const staffRef = db.collection("staff").doc(uid)
return staffRef.set({
employeeProfile: employeeProfile
}, {
merge: true
})...
Is there any way to check if that document exist on set or should I first read it to find out if that document exist like this
const staffRef = db.collection("staff").doc(uid)
return staffRef.get()
.then((doc) => {
if (doc.exists) {
return staffRef.set({
employeeProfile: employeeProfile
}, {...
Second I want to check multiple documents on where
const staffRef = db.collection("staff").where("employerId", "==", uid)
const batch = db.batch()
return staffRef.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
batch.update(doc.ref, { employerProfile: employerProfile })
})...
Should I read the each doc after forEach if exist?
First answer: Yes, for a single document, you have to first use the get()
method to find out if that document exists.
For a
DocumentSnapshot
that points to a non-existing document, any data access will return 'undefined'. You can use theexists
property to explicitly verify a document's existence.
Second answer: No, in case of the results of a Query
, you don't need to check each document: each doc
you get by looping with querySnapshot.forEach()
does exist.
A
QuerySnapshot
contains zero or moreDocumentSnapshot
objects representing the results of a query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.