Firebase Firestore: How to check if the document exists before writing data?

Viewed 3586

I want to check if the document actually exists in the path before uploading data. If not, it will set a new document to the path. If yes, it will just update the data.

Couldn't find a way to do this in the documentation. What will be the best way to do this? Here is what I think will look similar. Any suggestions? Thanks!

const ref=firebase.firestore().collection('posts').doc('post_id');
if (!ref.exists) {
     firebase.firestore().collection('posts').doc('post_id').set(data);
}
else {
     ref.update(data);
}
1 Answers

The set() method with the merge option is what you are looking for:

If the document does not exist, "it will set a new document to the path", if it exists "it will just update the data".

You have to do as follows:

const ref = firebase.firestore().collection('posts').doc('post_id');
ref.set(
  {foo: 'bar', bar: 'foo'},
  {merge: true}
);
Related