FireStore create a document if not exist

TSR picture TSR · Sep 11, 2018 · Viewed 20.1k times · Source

I want to update a doc like this:

db.collection('users').doc(user_id).update({foo:'bar'})

However, if the doc user_id does not exists, the above code will throw an error. Hence, how to tell Firestore to create the student if not exists, in other word, behave like this:

db.collection('users').doc(user_id).set({foo:'bar'})

Answer

J. Doe picture J. Doe · Sep 11, 2018

I think you want to use this code:

db.collection('users').doc(user_id).set({foo:'bar'}, {merge: true})

This will set the document with the provided data and will leave other document fields intact. It is best when you're not sure whether the document exists. Simply pass the option to merge the new data with any existing document to avoid overwriting entire documents.

For more detailed about managing data with firestore check this link