I am trying to retrieve specific data from firebase, in my redux store I have uniq id that I can get in any page like this
const currentUser = useSelector(selectLoggedInUser);
console.log(currentUser.id) // "71dc954d-d2a4-4892-8257-98696fe776cd" this is peace of doc name in "dms" collection
I want all doc-s that contains this ID "71dc954d-d2a4-4892-8257-98696fe776cd", how can I query it??? This is how I'm setting "dms" messages
export const sentDirectMsg = async ({ toUid, currentUid, message, name }) => {
const collecitonRef = await dmCollection(toUid, currentUid);
await addDoc(collecitonRef, {
timestamp: serverTimestamp(),
message,
name,
});
};
const dmCollection = async (toUid, currentUid) => {
const idPair = [currentUid, toUid].sort().join("_");
return collection(db, "dms", idPair, "messages");
};
CodePudding user response:
If your data model is centered toward users being identified through their unique IDs, then you can store your data first hand to reflect his model:
const userData = {
name: 'Marouane',
state: 'BN',
country: 'TUN'
};
// Add the user document in collection `dms`, with the id being the user ID
const res = await db.collection('dms').doc('71dc954d-d2a4-4892-8257-98696fe776cd').set(userData);
You can then query the user document using its unique identifier:
const userRef = db.collection('dms').doc('71dc954d-d2a4-4892-8257-98696fe776cd');
const doc = await userRef();
if (!doc.exists) {
console.log('No such user!');
} else {
console.log('User dms data:', doc.data());
}
CodePudding user response:
Edited:
If I understood correctly, you want to get a document which id contains a part of the id you are looking for.
Using array-contains should do the trick:
const dmsRef = collection(db,"dms");
const docRef = query(dmsRef, where("idPair", "array-contains", id)); //for example id = "71dc954d-d2a4-4892-8257-98696fe776cd"
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
I based my example on this link from the official documentation.