Reputation: 2771
I have a use case where I need to delete a document that may or may not exist. I delete like this
db.collection('cities').doc('DC').delete();
It works fine, but when the document doesn't exist, I get an error in the log, which I'd rather not see. I could read the document first to ensure it exists, but that seems wasteful. What's the proper delete-if-exists approach?
EDIT I'm performing this operation using Cloud Functions (JS)
Upvotes: 0
Views: 274
Reputation: 1181
You can also use async/await and reuse the same doc for both actions
const doc = db.collection('cities').doc('DC')
const snapshot = await doc.get()
if (snapshot.exists) await doc.delete()
Upvotes: 0
Reputation: 18096
db.collection('cities').doc('DC').get().then(
doc => {
if (doc.exists) {
db.collection('cities').doc('DC').delete().then(() => {
console.log("Doc deleted!")
})
}
}
);
Upvotes: 2