Why ref.getCollections() is not recognized as a function? - javascript

I'm doing a website which store users data on cloud firestore. I use this to get all subcollections of a user document once:
db.collection('users').doc(userID).getCollections().then( collections => {
/*I get my collections and I enjoy it :D*/
})
The problem is that this function is not recognized. I find this message on the console:
TypeError: db.collection(...).doc(...).getCollections is not a function
I know I could get the all subcollections otherwise but I want to save the maximum of readings because of de limited quota. All others firebase functions work in my project (like get() or set()) and getCollections() is in the documentation.
Thank for your help !

Google team was replaced method name from 'getCollections' to 'listCollections'. So you should update this method name again.
Reference at here https://googleapis.dev/nodejs/firestore/latest/DocumentReference.html#listCollections
It works for me with these tool versions: firebase-tools v7.2.1, firebase-admin v8.3.0, firebase-functions v3.2.0.

In your example db.collection('users').doc(userID) returns DocumentReference
and as far I can see DocumentReference object doesn't support getCollections method
Here is the documentation https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference

Related

Why am I getting this firebase/firestore error?

Here is my query
const query = messagesRef.where('members', 'in', [`${currentUserId}`]).orderBy('createdAt')
I have created an index as well.
This is the error I get
Error: {"code":"failed-precondition","name":"FirebaseError"}
Which I assume is usually an index thing
Yes, the failed-precondition can be due to a missing index. It can also be manually thrown by a user though with any user-defined description, typically from within a Firebase Function. The category is the only thing that must confine to the convention:
https://cloud.google.com/datastore/docs/concepts/errors
Here's one example of such error common in App-Checked Firebase Functions:
if (context.app == undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.')
}
You may want to check your Function Logs to get the actual error description. If the issue happens locally, then your firestore-debug.log file should contain some useful information. Just to be certain it's actually an index issue or not.
If the issue is happening only on production, you may want to verify the contents of your firestore.indexes.json and compare to what's inside the Firebase Console under https://console.firebase.google.com/u/0/project/<PROJECT-NAME>/firestore/indexes.
If it's actually an index issue, there will be a URL provided inside the logs that you can click which will generate the index for you inside Firestore:
https://firebase.google.com/docs/firestore/query-data/indexing?authuser=0&hl=en#create_a_missing_index_through_an_error_message
I hope this helps track down the issue! I used failed-precondition for several different error types, some unrelated to Firestore or indexes.

Creating continuous receiver for session enabled subscription from Azure Bus Topic

We are having a session-enabled azure bus topic. This topic can have multiple messages with distinct session IDs. We want to create a listener/receiver that keeps reading messages from the Topic. As we have multiple dynamic session IDs, we can not use acceptSession to create a handler. We have tried using the methods createReceiver and acceptNextSession methods of ServiceBusClient but they have the following issues
CreateReceiver: This method does not work on session-enabled subscriptions giving a runtime error.
acceptNextSession: This method only listens to the first message and does not read further messages.
Our Current code is :
const serviceBusSettings = this.appSettings.Settings.serviceBus;
const sbClient = new ServiceBusClient(serviceBusSettings.connectionString);
//const receiver = sbClient.createReciver(topicName, subscriptionName);
const receiver = sbClient.acceptNextSession(topicName, subscriptionName);
const handleTopicError = async (error: any) => {
this.logger.error(error);
throw error;
};
(await receiver).subscribe({
processMessage: handleTopicMessage, // handleTopicMessage is a method passed as an argument to the function where this code snippet exists
processError: handleTopicError
});
We also tried implementation one of the sample code repo wiki. But the methods shared in the example seems to be no longer available in new npm version of #azure/service-bus Link to tried example
Can anyone suggest some solution to this?
There's a sample showing how you can continually read through all the available sessions. Could you please check to see if it is helpful?
https://github.com/Azure/azure-sdk-for-js/blob/21ff34e2589f255e8ffa7f7d5d65ca40434ec34d/sdk/servicebus/service-bus/samples/v7/javascript/advanced/sessionRoundRobin.js

How do you add multiple documents at once to a collection in Firestore?

I am somewhat new to Firebase and looking for the ability to write multiple JSON objects into a collection under random IDs in one operation. I am just using firestore and auth(not shown) along with react.
So far I have
Function TestDocs () {
{addDoc(collection(db, 'randomData'), {**object 1 example data**},{**object 2 more example data**}
)
}
I have a button on a webpage which adds the data into the DB. When I check Firestore only the first object is loaded and not the second... on top of this, assuming that I wanted to add hundreds of objects(not just 2), how would I go about this?
I was looking through the documentation for Firestore batch writes but it only lists set(), update() and delete() as permitted operations so I am not sure how it would work. Thanks in advance
You'll want to do this in two steps:
Create a reference to a new document with a new unique ID:
// Generate two new document references with a generated ids
const newRef1 = doc(collection(db, "randomData"));
const newRef2 = doc(collection(db, "randomData"));
Write to that reference in your batch or transaction.
Also see:
Firestore - batch.add is not a function (which contains the older namespaced syntax for doing the same).
The last snippet in the documentation on adding a document, which shows this approach.
I found another way to do this without using Firebases batch function. Each transaction or batch of writes can write to a maximum of 500 documents. I was looking to update my app with more than 500 and found a video on YouTube showing another way to do this.
I had to tweak the script a bit to get what I needed but the idea is there.
https://www.youtube.com/watch?v=Qg2_VFFcAI8

Firestore get path of already queried document

I am trying to get the path of a queried document in Firebase Firestore. This is my code:
const location = await db.doc('/locations/US/regions/IOWA').get()
console.log(location.path)
However location.path returns undefined.
location.id works and returns the id.
I have used this as a resource: https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#path
When you call get() on a DocumentReference, you get back a DocumentSnapshot, which does not have a path property.
You're probably looking for location.ref.path.
The API documentation for DocumentSnapshot says that the reference of the document can be found in its reference property. So you will want to use this: doc.reference.
The currently accepted answer appears to be outdated, as aDocumentSnapshot does now store the path.
Every DocumentSnapshot has a DocumentReference found under the ref property (https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentSnapshot#ref)
In the DocumentSnapshot, you can then find a string representation of the path under the path property` (https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference#path)
In short, you can simply use doc.ref.path to get the path.
I know it is old and answered question, this is how I get the document reference from queried document
d.get()
.then(td=>{
let taskDep = td.data()
taskDep.id = td.id
taskDep.ref = td.ref
})

QueryDocumentSnapshot seems to lack the methods of its parent class

I'm using firebase to build a database application. I'm trying to get the firebase generated id of a particular document. The document is returned as a Promise, which returns a QuerySnapshot. A forEach loop pulls each QueryDocumentSnapshot out of the QuerySnapshot, so I'm working with the QueryDocumentSnapshot class. The documentation says that this class has the same API surface as the DocumentSnapshot class.
https://developers.google.com/android/reference/com/google/firebase/firestore/QueryDocumentSnapshot
Since the DocumentSnapshot class has a getId() method, I thought I'd use that.
searchBooks(){
this.booksSearched = true;
this.bookService.getBookList(this.authorName).get().then(bookListSnapshot =>{
this.bookList = [];
bookListSnapshot.forEach( snap =>{
this.bookList.push({
authorLastName: snap.data().authorLastName,
title: snap.data().title,
edition: snap.data().edition,
id: snap.getId() <-------ISSUE HERE-----------
});
return false;
});
});
}
However, I get this error.
property 'getId' does not exist on type 'QueryDocumentSnapshot'
Here is the code for the bookService
getBookList(authorLastName): firebase.firestore.Query{
return this.bookListRef.where("authorLastName", "==", authorLastName);
}
What's even more wild is when I tried change my code around. Instead of pulling the QueryDocumentSnapshots out using the forEach loop, I thought I would take advantage of the fact that bookListSnapShot is a QuerySnapshot and call its getDocuments() method. https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/QuerySnapshot
This would return a list of DocumentSnapshots, possibly meaning that whatever inheritance issue with the getId() method could be avoided. However, when I tried, I got this error:
var documents = bookListSnapshot.getDocuments();
Property 'getDocuments' does not exist on type 'QuerySnapshot'
To me, it seems like the documentation is being contradicted by the errors the editor is throwing. Does anyone know what's going on?
Thank you for reading,
-Joel
You're writing code in JavaScript, but you're looking at API documentation for Android using Java. Here are the JavaScript API docs for DocumentSnapshot and QueryDocumentSnapshot. DocumentSnapshot has a property called id that you're looking for.

Categories