![](/img/trans.png)
[英]How to check id IndexedDB already exist inside of React lifecycle methods
[英]How can I check if the id already exist in React using firestore?
这是我将数据添加到 Firestore 的代码。 如何检查集合中是否已存在 idEveniment 字段? 如果存在,我不想添加新集合。 也许返回错误?
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})
}
}
在您当前的数据结构中,您无法检查具有特定值idEveniment
的文档。 您可以使用array-contains
来检查数组成员资格,但前提是您指定了idEveniment
和eveniment
的组合。
如果您希望能够仅检查idEveniment
的值,请考虑将字段idEveniments
添加到每个文档中仅具有该值。 然后,您可以使用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.