Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore retrieve single document by field value and update

I'm trying to retrieve a single document by a field value and then update a field inside it. When I do .where("uberId", "==",'1234567'), I am getting all the docs with field uberId that matches 1234567. I know for sure there is only one such document. However, I don't want to use uberId as the document's ID, otherwise I could easily search for the document by ID. Is there another way to search for a single document by a field ID?

So far, reading the docs, I could see this:

const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();

Then I suppose I could do const documentSnapshot = documentsSnapshot.docs[0] to get the only existing document ref.

But then I want to update the document with this:

documentSnapshot.set({
  happy: true
}, { merge: true })

I'm getting an error Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'

like image 336
Ben Avatar asked Oct 27 '25 09:10

Ben


1 Answers

While you may know for a fact there's only one document with the given uberId value, there is no way for the API to know that. So the API returns the same type for any query: a QuerySnapshot. You will need to loop over the results in that snapshot to get your document. Even when there's only one document, you'll need that loop:

const querySnapshot = await collectionRef.where("uberId", "==",'1234567').get();
querySnapshot.forEach((doc) => {
  doc.ref.set(({
    happy: true
  }, { merge: true })
});

What's missing in your code is the .ref: you can't update a DocumentSnapshot/QueryDocumentSnapshot as it's just a local copy of the data from the database. So you need to call ref on it to get the reference to that document in the database.

like image 174
Frank van Puffelen Avatar answered Oct 29 '25 23:10

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!