Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FireStore create a document if not exist

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'}) 
like image 454
TSR Avatar asked Sep 11 '18 13:09

TSR


People also ask

Does firestore Create collection if not exists?

Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.

How do I create a document in firebase?

Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.

How do you add a custom ID to firestore?

To add Document with Custom ID to Firestore with JavaScript, we call the set method. db. collection("cities"). doc("LA").

How do I get a random document ID in firestore?

An easy way to grab random documents is get all the posts keys into an array ( docA , docB , docC , docD ) then shuffle the array and grab the first three entries, so then the shuffle might return something like docB , docD , docA . Okay thats a good idea!


2 Answers

I think you want to use the following 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

like image 86
J. Doe Avatar answered Sep 20 '22 10:09

J. Doe


If you need things like created and updated timestamps, you can use this technique:

let id = "abc123"; let email = "[email protected]"; let name = "John Doe"; let document = await firebase.firestore().collection("users").doc(id).get(); if (document && document.exists) {   await document.ref.update({     updated: new Date().toISOString()   }); } else {   await document.ref.set({     id: id,     name: name,     email: email,     created: new Date().toISOString(),     updated: new Date().toISOString()   }, { merge: true }); } 

This will create the document if it doesn't exist with created and updated timestamps, but only change the updated timestamp if it exists.

like image 20
Dale Zak Avatar answered Sep 19 '22 10:09

Dale Zak