admin管理员组

文章数量:1323342

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?

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?

Share Improve this question edited Feb 5, 2019 at 20:20 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges asked Feb 5, 2019 at 18:54 DanielDaniel 7,7349 gold badges36 silver badges102 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Firestore can only update documents for which it knows the plete 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 remend 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.

本文标签: javascriptupdate cloud firestore document without idStack Overflow