Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 229
Daniel Avatar asked Oct 30 '25 21:10

Daniel


1 Answers

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.

like image 118
Frank van Puffelen Avatar answered Nov 02 '25 12:11

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!