Home > OS >  Updating Firestore if field exists
Updating Firestore if field exists

Time:11-18

I have a simple app that allows a user to input an email address and a date.

I have a collection within Firestore with document names auto-generated and the two fields saved there. Like this: enter image description here

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).

Any help would be fantastic.

Here is my JS so far:

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");

let querySnapshot = getDocs(q);
let q = query(collection(db, "candidates"), where("email", "==", "..."));

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)),

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

CodePudding user response:

I want to be able to update only the date if the email id is already in the database

You should first query the database to check if a document with the email exists and if it does you update the doc.

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.

  • Related