How to query for objects with a certain property in a Firestore collection, Firebase - javascript

I am trying to query for objects in firestore collection with a certain property, my Firestore DB looks as shown in the below picture.
The below code does not work as I am interested in querying for objects based on the the property inside an object. In this case I want all the cases (objects) with "status"=="treated" Is there a way to do it ?
const db = firebase.firestore();
const casesRef = db.collection("mgm/hospital/cases");
// Create a query against the collection.
var query = casesRef.where("status", "==", "active").limit(25);
const queryRef = query.get();
queryRef.then(function(documentSnapshots) {
const cases = documentSnapshots.docs.map((doc) => doc.data());
console.log(cases);
});

Since the field patientDetails is a map, the following should do the trick:
var query = casesRef.where("patientDetails.status", "==", "active").limit(25);

Related

How to get the complete document path in firebase firestore?

I managed to get all the documents and document IDs inside all 'sheets' collection in firestore.
Refer to below code -
const baseRef = admin.firestore().collectionGroup("sheets").where("date", "==", date);
const querySnap = await baseRef.get();
const docSnap = querySnap.docs;
docSnap.forEach((doc) => {
console.log("DOC ID ---->>>", doc.id);
// Here I want to get all the required documents from 'members' subcollection present inside this document
});
Now each of these documents contain a subcollection called 'members'. I want only documents from 'members' collection where "memberId" is equal to 'memberId'. How can I get those documents?
I tried the following code but it didn't worked -
const baseRef = admin.firestore().collectionGroup("sheets").where("date", "==", date).collectionGroup("members").where("memberId", "==", memberId);
const querySnap = await baseRef.get();
const docSnap = querySnap.docs;
docSnap.forEach((doc) => {
console.log("DOC ID ---->>>", doc.id);
});
It returned following error -
admin.firestore(..).collectionGroup(..).....is not a function
You cannot define a Query by calling twice the collectionGroup() method as you do with:
const baseRef = admin.firestore().collectionGroup("sheets").where("date", "==", date).collectionGroup("members").where("memberId", "==", memberId);
One solution would be to replicate the date field in the member documents (i.e. copying the field value from the parent sheet docs to their member children docs) and define the Query as follows:
const baseRef = admin.firestore().collectionGroup("members").where("memberId", "==", memberId).where("date", "==", date);
Note that you'll need to build a composite index and that you should not have other subcollections named members in your database.

What does .where.get() return?

i am new this website and to mobile programming.
My questions is:
In firebase i have a collection path with some documents.
.collection(maybe).doc(random)
Each doc has subcollection as well.
Also each doc has data such as:
roomName: randomName
roomPassword: randomPass.
So, now i would like to use the query with .where operator and .get like this:
const docRef=db.collection(‘maybe’)
docRef.where(‘roomName’ ‘==‘ ‘randomName’).get()
My question is what do i get back? As i understand i get the querySnapshot, but i do not fully get how to get the second field in data specifically i.e. how to get roomPass?
const docRef = db.collection(‘maybe’);
const futureSnapshot = docRef.where(‘roomName’,‘==‘,‘randomName’).get();
gives you a promise of snapshot.
You have to "await".
const docRef = db.collection(‘maybe’);
const snapshot = await docRef.where(‘roomName’,‘==‘,‘randomName’).get();
after that you can get your data :
const room = snapshot.data(); // undefined if your query has no results
This link could help you
Happy coding !
EDIT
If your document looks like this :
{
randomName: "a name",
randomPassword: "a password"
}
Then you get your data like that :
const room = snapshot.data(); // undefined if your query has no results
const { randomPassword } = room;

In IndexedDB how can I return the value from an object for all the records in the DB?

I have several objects stored in my IndexedDB objectStore. These objects each have several keys, one of which is the name of the sports team. Example of my object:
What I'm trying to do is get the value of full_name for each of these objects. Can I do this by directly querying IndexedDB with the objectStore.getAll() method? My code currently looks like this:
async getData() {
const db = await openDB('nbaPlayersTeams', 1);
const tx = db.transaction('nbaPlayersTeamsStore', 'readonly');
const store = tx.objectStore('nbaPlayersTeamsStore');
const allTeams = await store.getAll();
console.log(allTeams);
db.close();
}
Thanks,
Bez

How to find out if a record exists in Firestore (node)

Something that was so easy in firebase database, impossible for me to accomplish in firestore. I just need to know if a record exists in a specified document.
const user = firebase.auth().currentUser.uid;
const currentPostId = this.posts[index].id;
const ref = db.collection(`likes`).doc(`${currentPostId}`); // need to know if this doc has records
The post has a store of records with just the userids that have liked the post, and a timestamp.
So far I'm able to do this:
const ref = db.collection(`likes`).doc(`${currentPostId}`);
ref
.get()
.then(snapshot => {
console.log("Exists?" + snapshot.exists); //true
})
But for the life of me I just CANNOT find a way to go one level deeper.
const ref = db.collection(`likes`).doc(`${currentPostId}/${user}`); //invalid reference segments must be odd numbers
const ref = db.collection(`likes`).doc(currentPostId).collection(user) //undefined
I've spent tthree days trying different ways. in firebase database it was just:
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var a = snapshot.exists(); // true
var b = snapshot.child("name").exists(); // true
var c = snapshot.child("name/first").exists(); // true
var d = snapshot.child("name/middle").exists(); // false
});
You can read the document and check whether the document has a field with the user id.
const ref = db.collection(`likes`).doc(currentPostId);
ref
.get()
.then(doc => {
console.log("Exists?" + doc.exists); //true
if(doc.exists){
var documentData = doc.data();
// Check whether documentData contains the user id
if (documentData.hasOwnProperty(userId)) {
// do something
}
}
})
The code above is not tested but it should work.
A hint! You can and should store timestamps, which are generated on the client side with the firestore server timestamp:
admin.firestore.FieldValue.serverTimestamp();
Because, if the client have changed the local time you could get a wrong time.

Firebase Database: why do the key/ref in my queried datasnapshot refer to its parent?

I would like to delete an entry from the realtime database that i looked up through a query but i am getting unexpected results for both the ref and key properties.
ref('photos/users/USERID')
.orderByChild('photoname')
.equalTo('photoname i want to look up')
.limitToFirst(1)
.query('once')
.then(snapshot => {
// correct data at 'photos/users/USERID/PHOTOID'
const entry = snapshot.val();
// seems to be the ref to photos/users/USERID'
const ref = snapshot.ref;
// seems to be USERID
const key = snapshot.key
})
Why aren't these the ref/key to the entry i just found? And what is the best approach to remove this entry?
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to take this list into account, and iterate over snapshot.forEach() to get the actual matching item:
ref('photos/users/USERID')
.orderByChild('photoname')
.equalTo('photoname i want to look up')
.limitToFirst(1)
.query('once')
.then(snapshot => {
snapshot.forEach(child => {
const entry = child.val();
const ref = child.ref;
const key = child.key
});
})
Your ref and key are based on ref('photos/users/USERID'), not the filtered subset you have created. Is there any reason you wouldn't call ref('photos/users/USERID/PHOTOID')?

Categories

Resources