Ben
Ben

Reputation: 3357

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>'

Upvotes: 4

Views: 9102

Answers (2)

Most Wanted
Most Wanted

Reputation: 6989

async function getUserByEmail(email) {
  // Make the initial query
  const query = await db.collection('users').where('email', '==', email).get();

   if (!query.empty) {
    const snapshot = query.docs[0];
    const data = snapshot.data();
  } else {
    // not found
  }

}

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598718

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.

Upvotes: 10

Related Questions