简体   繁体   English

如何使用 firestore 检查 id 是否已存在于 React 中?

[英]How can I check if the id already exist in React using firestore?

This is the code where I add data to firestore.这是我将数据添加到 Firestore 的代码。 How can I check if idEveniment field already exist in collection?如何检查集合中是否已存在 idEveniment 字段? And if exist I dont want to add the new collection.如果存在,我不想添加新集合。 Maybe return an error?也许返回错误?

import { firestore } from 'firebase';

// Add Eveniment
export const addEveniment = data => async(dispatch, getState, {getFirestore}) => {
    
    const firestore = getFirestore();
    const userId = getState().firebase.auth.uid;
    dispatch({type: actions.ADD_EVENIMENT_START});
    try {
        const res = await firestore.collection('evenimente').doc(userId).get();
        
        const newEveniment = {
            idEveniment: data.idEveniment, 
            eveniment: data.eveniment,
        }
        if(!res.data()) {
            firestore.collection('evenimente').doc(userId).set({
                evenimente: [newEveniment],
            });
        } else {
            firestore.collection('evenimente').doc(userId).update({
                evenimente: [...res.data().evenimente, newEveniment],
            });
        }
        

        dispatch({type: actions.ADD_EVENIMENT_SUCCESS});
        return true;
    } catch(err) {
        dispatch({type: actions.ADD_EVENIMENT_FAIL, payload: err.message})
    }
        
}

Firestore 集合

In your current data structure you can't check for documents with a specific value of idEveniment .在您当前的数据结构中,您无法检查具有特定值idEveniment的文档。 You can use array-contains to check array membership but only if you specify the combinarion of idEveniment and eveniment .您可以使用array-contains来检查数组成员资格,但前提是您指定了idEvenimenteveniment的组合。

If you want to be able to check just on the value of idEveniment , consider adding a field idEveniments to each document with just that value.如果您希望能够仅检查idEveniment的值,请考虑将字段idEveniments添加到每个文档中仅具有该值。 Then you can use array-contains for the existing of a specific idEveniment value in the idEveniments array:然后,您可以使用array-contains来表示idEveniments数组中存在的特定idEveniment值:

const evenimentesRef = firebase.firestore().collection("evenimente");
const query = evenimentesRef.where("idEveniments", "array-contains", "376342").limit(1);
query.get().then((snapshot) => {
  if (!snapshot.empty()) {
    ... a document with the value already exists
  }
});

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

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