简体   繁体   English

如果字段存在则更新 Firestore

[英]Updating Firestore if field exists

I have a simple app that allows a user to input an email address and a date.我有一个简单的应用程序,允许用户输入 email 地址和日期。

I have a collection within Firestore with document names auto-generated and the two fields saved there.我在 Firestore 中有一个集合,其中自动生成文档名称并将两个字段保存在那里。 Like this:像这样: 在此处输入图像描述

I want to be able to update only the date if the email id is already in the database (not much help if it updates the email address for a matching date as there will be many duplicate dates).如果 email id 已经在数据库中,我希望能够只更新日期(如果它更新匹配日期的 email 地址没有太大帮助,因为会有很多重复日期)。

Any help would be fantastic.任何帮助都会很棒。

Here is my JS so far:到目前为止,这是我的 JS:

const db = getFirestore(firebaseApp);
const btn = document.getElementById("btn");

const docRef = btn.addEventListener('click', (e) => {
    let mail = document.getElementById("email").value;
    e.preventDefault,
    setDoc(doc(db, "candidates", mail), {
        email: document.getElementById("email").value,
        date: Timestamp.fromDate(new Date(document.getElementById("date").value)),
    });
});

Issue solved, final working code:问题已解决,最终工作代码:

const db = getFirestore(firebaseApp);
const btn = document.getElementById("btn");


const docRef = btn.addEventListener('click', (e) => {
    let mail = document.getElementById("email").value;
    e.preventDefault,
    setDoc(doc(db, "candidates", mail), {
        email: document.getElementById("email").value,
        date: Timestamp.fromDate(new Date(document.getElementById("date").value)),

    
    });
});

const candidateRef = doc(db, "candidates", mail);

await updateDoc(candidateRef, {
  date: date
});

I want to be able to update only the date if the email id is already in the database如果 email id 已经在数据库中,我希望能够只更新日期

You should first query the database to check if a document with the email exists and if it does you update the doc.您应该首先查询数据库以检查是否存在带有 email 的文档,如果存在则更新文档。

Something along the following lines (we make the assumption that there is only one document per email):大致如下(我们假设每封电子邮件只有一个文档):

import { collection, query, where, getDocs, updateDoc } from "firebase/firestore";

const q = query(collection(db, "candidates"), where("email", "==", "..."));

const querySnapshot = await getDocs(q);
if (querySnapshot.size === 1) {
   const docRef = querySnapshot.docs[0].ref;
   await updateDoc(docRef, {...});
}

Note that you may use a Transaction depending on your functional requirements and data model. In this case you'll need to use the email as the document ID because you cannot use a Query in a Transaction with the JS SDK.请注意,您可以根据您的功能要求和数据 model 使用事务。在这种情况下,您需要使用 email 作为文档 ID,因为您不能在事务中使用 Query 与 JS SDK。

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

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