Can we trigger firebase cloud functions when we create a collection (not "document")? - firebase

I am trying to achieve a scenario where firebase triggers only once when a collection is created and not every time that a document is added to the collection. Let's say I want it to trigger only for the first document added to the collection and not for every other document added to the same collection. How can that be done? Please help !!!

There is no such trigger for Cloud Functions. Your trigger path must specify exactly one document, or use wildcards to specify a path that could possibly match many documents.
If you want to know what a collection contains its first document, you will have to either:
Maintain a count of documents in that collection (perhaps in yet another document in another collection), and trigger of the change of that value when it goes from 0 to 1.
Query all of the documents in the collection where a document was just created in order to figure out if it was the first one.
Both of these requires a fair amount of extra code - very much not trivial to implement correctly for arbitrary collections. They could also run into problems under heavy load. If these options won't work for you, I suggest figuring out another way to get you function to trigger at the right time.

While It's not possible to do directly. You can check if collection contains any elements, and if it does it means that it exists.
const result =await firestore.collection("collection").limit(1).get()
if(result.size){
// Collection exists
}

Related

Check if a document exists on Firestore without get() the full document data

So this is possible:
const docSnapshot = await firebase.firestore().collection("SOME_COL").doc("SOME_DOC").get();
console.log(docSnapshot.exists);
But it "downloads" the whole document just to check if it exists. And I'm currently working with some havier documents and I have a script where I just need to know if they exist, but I don't need to download them at that time.
Is there a way to check if a document exist without .get() and avoid downloading the document data?
It seems you are using the JavaScript SDK. With this SDK there isn't any way to only get a subset of the fields of a document.
One of the possible solutions is to maintain another collection with documents that have the same IDs than the main collection documents but which only hold a very small dummy field. You could use a set of Cloud Functions to synchronise the two collections (Documents creation/deletion).
On the other hand, with the Firestore REST API, it is possible, with the get method, to define a DocumentMask which defines a "set of field paths on a document" and is "used to restrict a get operation on a document to a subset of its fields". Depending on your exact use case, this can be an interesting and easier solution.

Unable to delete an item from multiple collections in firebase

I have two collection in firebase, say A and B. When I add an item to one of the collections, say A, it automatically adds to another collection B. But when I delete an item from collection A, it remains in the other collection B.
Shot from firebase console
When I delete an item from collection A, it remains in the other collection B.
I am unable to figure out how to make the items deleted in both collections?
Please help.
This is no relational DB. Cascadate updates/deletes are possible in relational DBs like Sql, Postgresql, Firebird... In No-SQL You do not have any relations one document to another. What' more it is desirable to have some data cloned in two or more documents rather than creating a separate doc for it.
But maybe You can achieve what You want by using reference type? I sow it once or twice, it might be a good idea to check it out. But be the description it is only a field with path/reference, no magic here.
By the official doc:
If you want to delete documents in subcollections when deleting a parent document, you must do so manually, as shown in Delete Collections.
So You either want to rethink The DB model or have to manualy track each wlement You want to delete.
You have two ways to do that:
From client side use batch write (more here)
DocumentReference doc_1_reference = firestore.collection("messages").document(doc_1_uid);
DocumentReference doc_2_reference = firestore.collection("messages").document(doc_2_uid);
final batchWrite = firestore.batch();
batchWrite.delete(doc_1_reference);
batchWrite.delete(doc_2_reference);
await batchWrite.commit();
Using Cloud functions by adding a delete trigger to the documents, and perform the deletion of the other document when triggered. Given you have away to know which document you're supposed to delete which is not difficult to do (read about it here)

Would executing the below given code will delete all the previous data?

What if some data is already there inside the users collection ?
Would doing this 👇🏻 will delete all the previous data ?
var messageRef = db.collection('users').doc(userID)
.collection('private_user_data').doc(userID);
I want to add new data inside users collection and inside that a doc with 4 fields and one more collection inside that and inside that a doc with four more fields.
The code in your question doesn't read from or write to the database in any way. It merely sets up a reference to a document in the database.
There are few ways to implement this, depending on your exact use-case:
To merge data with an existing document, use the update method.
If the document may or may not exist, you can tell Firestore to merge the new values with the existing data when you call the set method.
If you want to set some fields only if the document doesn't exist yet, and leave them unmodified if the document already exists, you will need to use a transaction. In that case you may also want to make sure your security rules reject modifications to those initial fields.
With your code you don't make any operation on your db.
If you would know use .set(someData) your document would be created with given data if there is no document with given id or the document would be overwritten with the given data if there is a document with the given id.
Please check this post from the Firebase docs for more information.
EDIT
To create a document you have to do something like this:
var messageRef = db.collection('users').doc(userID)
.collection('private_user_data').doc(userID);
messageRef.set({
field1: input1,
field2: input2,
field3: input3,
field4: input4
})
Be aware that messageRef.set() will return a promise. So you have to deal with it. And here I would recommend you one of the tutorials from the Firebase team or one of many from the Internet.

How do I create a Firebase collection?

So I am writing a chat application that I want to have multiple rooms, however, I can't find a button on the Firebase console that I can add child collections.
I've tried exporting, editing, then importing but that doesn't seem to do much. I have looked at some Firebase tutorial's but I can't find one that explains this.
Anything you enter in the console has to have a value itself, or at least one child (with a value). This is because Firebase does not explicitly store "null" or empty values in the database. You can enter the name of the collection and then rather than a value use the + button at the right to start adding children to it and so on until you reach a node with a value:
You cannot however simply create a placeholder for a collection that has no values. If you need a collection but can't initialize any of its data, just use your security rules to define what's allowed and write your client code knowing it may or may not exist. Firebase allows you to attach listeners to nodes that don't exist yet.

How do I stop Firebase from creating an additional nested object or how can I access the newly generated string?

Problem: Whenever I add an order to the orders array, an additional nested array element(-KOPWA...) gets added. I wouldn't mind except, I don't know how to access that nested string to access it's child nodes.
Example of database node for users below:
firebase.database().ref('users/'+userIdState+'/orders/'+<<unique numbervariable>>).push({
"order":{"test":"product","quantity":2}
});
I'm using the above code to push new json objects with a unique number to the firebase array. Still the nested array with the weird strings gets generated.
Can anyone help me understand how to either: create my own nested array with my own unique string or how to access the nested string that gets generated from firebase so I can access it's children nodes.
Multiple instances of nest arrays will be generated by users.
Any help is much appreciated.
Thanks,
Moe
You're experiencing this behaviour because Firebase's push is not the same as an array push. I recommend reading this article to understand how it works.
As for a solution, you can simply change push to set in your code. This will create the structure you were (presumably) expecting, that is
1:
order:
...
This is however potentially unsafe, if you allow concurrent writes (i. e. if the "unique number" in your example is not always unique).
Afaik Firebase recommends using push to safely create collections/"arrays". You can retrieve the generated key by calling the key property on the reference returned by push. Like this:
var ref = firebase.database().ref('users/'+userIdState+'/orders/'+<<unique numbervariable>>).push({
"order":{"test":"product","quantity":2}
});
var generatedKey = ref.key; // the value you're looking for
If you decide to use it, you can probably just drop the order number you have right now and just use the generated one.

Resources