简体   繁体   English

Firestore 按字段值检索单个文档并更新

[英]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 .当我执行.where("uberId", "==",'1234567') ,我得到了所有uberId字段与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.但是,我不想使用 uberId 作为文档的 ID,否则我可以轻松地通过 ID 搜索文档。 Is there another way to search for a single document by a field ID?还有另一种方法可以通过字段 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.然后我想我可以做const documentSnapshot = documentsSnapshot.docs[0]来获取唯一的现有文档引用。

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>'我收到错误Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'

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.虽然可能知道只有一个文档具有给定的uberId值,但 API 无法知道这一点。 So the API returns the same type for any query: a QuerySnapshot .因此,API 为任何查询返回相同的类型: 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.您的代码中缺少的是.ref :您无法更新DocumentSnapshot / QueryDocumentSnapshot因为它只是数据库中数据的本地副本。 So you need to call ref on it to get the reference to that document in the database.因此,您需要对其调用ref以获取对该数据库中该文档的引用。

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
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM