Where is the Firebase Admin SDK docs for interacting with Firestore? - google-cloud-firestore

The docs for using the Firebase Admin SDK with the Real Time Database are easy to find.
https://firebase.google.com/docs/database/admin/start
I can't find anything similar for how to use the Firebase Admin SDK with Cloud Firestore?
Been scraping for examples of using the Firestore Admin SDK with Firestore online and on StackOverFlow but feel like I am missing something.
For example I need to perform a query on a collection. The documentation for Firestore is great, https://firebase.google.com/docs/firestore/query-data/queries#web-version-9_3, but I can't find documentation on how to do the same with the same query on Firestore with the Admin SDK.

To use Admin SDK with firestore, simply follow the Node.js (not Web version 9) instruction in the link you gave.
For example, to perform query on a collection, do something like this:
// const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// below is given in the docs link
const citiesRef = db.collection('cities');
const snapshot = await citiesRef.where('capital', '==', true).get();
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
NB: The second link you sent is correct. Simply switch from Web version 9 to Node.js.

Related

Get collection inside document in Firestore with Firebase v9?

I have a Firestore collection inside of a document and I'd like to get the contents of provider:
I thought this would be easy enough but I'm stuck even after following the documentation on the official Firebase website.
I'm using Python 3 and Firebase Firestore v9.
productsCollectionRef = self.client.collection("products")
for productDocRef in productsCollectionRef.stream():
providerCollections = productDocRef.collections() # ERROR
for providerCollection in providerCollections: # There's only one sub-collection
for providerDocRef in providerCollection.stream():
print(providerDocRef)
The error I get at productDocRef.collections() is AttributeError: 'DocumentSnapshot' object has no attribute 'collections'.
What I've tried
The official Firebase doc sample: https://cloud.google.com/firestore/docs/samples/firestore-data-get-sub-collections#code-sample
Similar usage: Firestore: List subcollections of a document using python
DocumentSnapshot object docs: https://cloud.google.com/python/docs/reference/firestore/latest/google.cloud.firestore_v1.base_document.DocumentSnapshot?skip_cache=false#methods

How to test whether an ID is a valid MongoDB Object ID using Jest?

I am new to javascript and came across this problem. After searching for a solution on Google I realized that there is no such question asked on StackOverflow. After I figured out the solution I thought of sharing it here in case it helps someone.
I'm building a To-Do list app where a user is created with fields username (email), password, and DOB. I'm using MongoDB to store user and todo data. After the user is created, they can log into the app with their username and password.
When the user logs in, I need to get their userID from their username. The path I'm using to GET the userID is - /api/user/username/:username I'm using Jest for TDD so I need to write tests first for the above case.
One of the specifications out of different test cases in the test suite is: get UserID from username and return userID in MongoDB ObjectID format.
How do I check whether the userID returned is in MongoDB ObjectID format?
To check if a userID is a valid MongoDB ObjectID using Jest, one can use
expect(ObjectID.isvalid(userID)).toBeTruthy();
One example is as follows:
it(`must get userID when username is in valid email format & available in db and return userID in mongoDB ObjectID format`, async (done) => {
const response = await request(app)
.get(`/api/user/username/${username}`)
.set({ "x-token-header": jwtToken })
.send();
const { body } = response;
expect(ObjectID.isValid(body)).toBeTruthy();
done();
});

Flutter firestore limit the number of write operations a user is allowed

I'd like to know if there is a way to limit the number of write operations a user can make to a collection using flutter. For example if the user has already posted 5 documents, they should not be able to create any more until they delete some of the existing documents
You can store how many times the user has written to the database with a SharedPreference and then manage the UI in case it can or cannot load on Firestore.
Then every time a document is uploaded by that user, check with a cloud function that it has not exceeded the upload limit.
For anyone in future who might want to achieve something similar. I used the get() route to get the number of documents the user currently has in the firestore collection, then used if statement to implement my logic
Future checkuploads()async{
//check firestore for the number of posts the user currently has active
return FirebaseFirestore.instance
.collection('collecttionname')
.doc(userid)
.collection("othercollection")
.get()
.then((value) {
var count = 0;
count = value.docs.length;
if(count>=3){
//do something
}else{
//your upload function
}
//the call the above function where you need it
}

get collection names in a document fiestore flutter [duplicate]

I am using Firestore in my project, so i want to show all collection names in my project.
Is it posible to get all collection names from Firebase project.
Thanks..
There are limited public APIs to get a list of top-level collections. Mobile clients (Android, iOS, web) have no API. Node.js admin clients have listCollections() on Firestore to get that list. Or, if you're looking for subcollections nested under a document, use DocumentReference.listCollections().
If you want to get a list on any platform, you should maintain that list yourself in a known collection inside a known document id.
You can do the following:
const admin = require("firebase-admin");
const db = admin.firestore();
db.listCollections()
.then(snapshot=>{
snapshot.forEach(snaps => {
console.log(snaps["_queryOptions"].collectionId); // LIST OF ALL COLLECTIONS
})
})
.catch(error => console.error(error));
This works with NodeJS.
Remember that you will need to download firebase-admin and do the necessary configuration for Firebase server side.
You can make a separate collection(say listOfCollections) which contains all the other collection names as documents or in an array of strings in one document as an alternative.
Then, whenever you are adding a new collection first add its name to the listOfCollections.

Angular Cloud Firestore get data based on logged In User

I have a firestore which will look like this:
Cloud Firestore
So in few word I have some users which can log in to my application and create recipe.
And in 'My recipe' page I will have the list of recipes that a user is having.
So I have 1 collection 'User' and inside that 1 collection 'Recipes' with multiple recipes.
I have implemented the Firestore Google login and this is working as I get uid. etc... THis is inside auth.service.ts:
auth.service.ts
and I want to create a recipes.service.ts with a methode getRecipes() which will getRecipes under users/$(user.uid)/Recipes
anyone can help here? I dont find any tutorial to display data with subcollection.
Welcome to Stackoverflow!
For you to retrieve data of collections with nested collection, you can easily return one, by using a code similar to this: db.collection('users').doc('<user>').collection('Recipes').get(). Using like this, it will return the document with the subcollection, per user.
However, there is no way of getting the sub-collections together with all the documents at once. But, there is a good workaround available here, that for your case would be something like this:
this.firestoreService.colWithIds$('users').pipe(
switchMap((users: any[]) => {
const us = users.map((r: any) => {
return this.firestoreService
.col$(`users/${r.id}/recipes`)
.pipe(
map(recipes => Object.assign(user, {recipes}))
);
});
return combineLatest(...us);
})
).subscribe(users => console.log(users);
While I have not tested this code, I believe it's a good starting point for you, since this code is getting the users values mapped to it’s sub-collection observables. Those Recipes values however are mapped back to the user values, with the sub-collection Recipes data containing as a new property.
Let me know if the information helped you!