Skip to content
Advertisement

update cloud firestore document without id

My Cloud Firestore looks like this:

users
  ├────random_id_1───{name, email, ...}
  ├────random_id_2───{name, email, ...}
 ...
  └────random_id_n───{name, email, ...}

I want to update a document of users given I have an unique identifier for it that is NOT the random id of the document (suppose, for example, the name is unique and I want to use it as identifier).

How can I update a document identifying it by a field of it?

Advertisement

Answer

Firestore can only update documents for which it knows the complete reference, which requires the document ID. On your current structure, you will have to run a query to find the document. So something like:

firebase.firestore().collection("users")
  .where("name", "==", "Daniel")
  .get()
  .then(function(querySnapshot) {
    querySnapshot.forEach(function(document) {
     document.ref.update({ ... }); 
    });
  });

If you have another attribute that is unique, I’d always recommend using that as the IDs for the documents. That way you’re automatically guaranteed that only one document per user can exist, and you save yourself having to do a query to find the document.

Advertisement