I have a users collection in which there are users based on ids, and each of them has a field called goal. I’d like to check if that goal field is empty or not in order to perform other actions/show other fields etc but I cannot figure out a way to do so.
What I am mostly confused about is the usage of the queries, I have found several different methods and none works, and I am not sure about all the updates and all.
I have the newest version of firebase, firestore and react.
My firebaseconfig:
// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
// Your web app's Firebase configuration
const firebaseConfig = {
...
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export const db = getFirestore(firebaseApp);
export default firebaseApp;
An example of how I fetch data into a list:
const [goals, setGoals] = useState([]);
const fetchPost = async () => {
await getDocs(collection(db, "goals"))
.then((querySnapshot)=>{
const newData = querySnapshot.docs
.map((doc) => ({...doc.data(), id:doc.id }));
setGoals(newData);
console.log(goals, newData);
})
}
useEffect(() => {
fetchPost();
}, []);
This is what I have now:
let user = firebase.auth().currentUser;
var userEmail = user.email;
let userName = userEmail.match(/^([^@]*)@/)[1];
let userId = user.id;
const [currentGoal, setCurrentGoal] = useState([]);
const fetchPost = async () => {
await getDocs(collection(db, "users"))
.then((querySnapshot)=>{
const newData = querySnapshot.docs
.map((doc) => ({...doc.data(), id:doc.id }));
if(doc.id === userId )
setCurrentGoal(newData);
console.log(currentGoal, newData);
})
}
useEffect(() => {
fetchPost();
}, []);
But the problem is 1. the user id is not working (I don’t know how to use it in a query) and I am unsure how to get the information about the goal field.
Here is my collection to make it more clear:
I have tried these practices but didn’t work:
- db.collection("users").where("email", "==", usersEmail)
.get() …… - the one tht starts with firestore(). … -> it says firestore is not defined
2
Answers
If you’re asking how to query for the document ID in the v9 SDK, that’d be:
Also see my answer here: Firestore – Web version 9 – get all documents in collection whose id is in array of ids
You can use
Object,hasOwnProperty("goal"))
anddoc.data().goal !== "")
to check if the goal property exist or is empty as follows:As from the details you shared it looks like you are storing the goals just as a string field. Hence why I have used currentGoal as a string property.
Reference :
Object.hasOwnProperty()