Firestore doesn't creates parent Document - javascript

I'm working on a Webapp that lets users save ideas.
When a idea gets saved, it is saved in the collection "users" which contains their user uid. Under the users Id is then again a collection named "ideas" created in which finally the ideas get saved.
The problem is, that when i save the idea, everything works fine, but the User ID is greyed out.
This leads to that i can't retrieve the ideas for a user, because the user id document isn't created.
The view in firestore:
The function that i use to create the documents:
The function to retrieve the data:
I can retrieve the ideas of a user correctly, when i create the users id entry manualy.
Do i need to check for the existence of a users document before saving the ideas into it and if it doesn't exists create it?
Or is there a better way im not aware of?

You need to create the user document, otherwise you will create a dangling collection without a parent document.
The id is greyed out, because the document does not actually exist and is only displayed because of the collection under it.

Related

Can only get one single document by id in a Firestore collection

I am stuck with a very strange bug and I can't understand why it is happening.
I have a collection in the Google Firestore called previews, in the collection, I have 4 documents that I manually inserted into the Firestore with automatically generated ids.
When I try to get the documents by id, only one of them is retrievable from the JavaScript side. I've been able to reproduce the problem with the query builder of the Firestore:
You can clearly see the documents here with their ids.
When I query BEOEGqnl7wBXCB6G4RLP, it works:
But when I query any other document, I get no result, even though they do exist!
I tried to change the properties of the documents, I also thought it may be some invisible space, but I checked that too. I don't see any difference between the documents, except for the data that's in them.
Any idea of what could be wrong?
Thank you!
I have 4 documents that I manually inserted into the Firestore with automatically generated ids.
There's a high chance you added a space either at the start or end of the document ID in the data or while querying.
To confirm if the issue is with the document ID, you can open that document in panel view and check the URL. The document ID should be right after ~2F and then check for any encoded characters like %20 in this case.
Alternatively, print the document IDs with quotes:
const snap = await getDocs(collection(db, "previews"))
snap.forEach((d) => console.log(`'${d.id}'`))

How to get Firebase array of documents ids from colletion where documents have No Data but only sub collections?

I don't know if this is a bug with Firebase, or maybe it's stated in their documentation, I can't get the IDs from the collection where the document has No fields but Only Subcollection. Please assist me with this. I tried to put some field on some document, then it has shown, then I deleted it again still it shows and I confirmed it's not Cache by opening Incognito on Chrome and still the document was only one showing even though I deleted the field I was testing with. My collection structure looks as on the image attached What I am trying to get is the Ids inside invoices. My current code is I am using Javascript:-
async getMarker() {
const snapshot = await this.db.collection("customer_invoices").get()
return snapshot.docs.map((doc: any) => doc.id);
}
There is no way to query those parent documents, as they don't exist. The console only shows these placeholders so that you can navigate to the subcollections.
The only way I can think of to get these IDs is to do collection group query on all your invoices subcollections, and then find the parent document of each invoice.
Also see:
Get parents from Firestore Collection Group Query, WITHOUT RETRIEVING SONS

Firestore (javascript sdk) - Get only new data (not just adding)

Im using Firestore with web javascript sdk.
Assume following scheme:
User Doc -> Friends collection
I want to know when someone change/remove/add data to it.
so what I wrote is something like this:
friendsCollectionRef.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
onChange(change);
});
});
The problem is that whenever I refresh the page, it keeps calling the onChange with data that was updated in my last session..
Is there a way to get only NEW data and not retroactively?
I would like to avoid store "LastUpdate" field on everything.
This, of course, should not be done in client side because then I pay for network which im never going to use..
So storing a boolean isFirstCall in out of the question.
As explained in the doc, when you listen to multiple documents in a collection with the onSnapshot() method:
The first query snapshot contains added events for all existing
documents that match the query. This is because you're getting a set
of changes that bring your query snapshot current with the initial
state of the query.
So each time you refresh your page you are calling again the onSnapshot() method "from scratch" and therefore you get the first query snapshot with all the collection docs.
In other words, I think you will have to implement your "home-made" mechanism to only get the documents you want (probably a "LastUpdate" field...).
You may be interested by this SO answer which shows how to add a createdAt timestamp to a Firestore document via a Cloud Function. You could easily adapt it to record the last update. It would be more complicated if you want to detect the Documents that were deleted since the last fetch.

How to update the document ID in firebase firestore? [duplicate]

This question already has answers here:
How to move a firestore document from cloud functions?
(2 answers)
Closed 4 years ago.
in my firestore database, I've made the user's email as the document key. Do if I want I cal do db.collection('users').doc('email_id') to perform some action. Now the problem is when the user is updating their email id, I am not finding any way to update the document id in firestore.
I've tried to do
db.collection('users').doc(old_email).update({
id: new_email
})
But that actually created a new field called id with the new email as value inside that document instead of updating the actual document id so that I can pass it within doc() and get the same data about the user.
Does anyone know how to do it? If so, please do share.
before posting this question I have checked google and firestore docs but didn't find any way to update the document id. Please help.
There is no API to change the ID of an existing document, nor is there an API to move a document. If you want to store the same contents in a different document, you will have to:
Read the document from its existing key.
Write the document under its new key.
Delete the document under its old key.
You'll want to run these operations in a transaction, to ensure the operations complete atomically.
I dont think there is a way to Change the Document ID, but even if there is a way what you do is horribly wrong. The ID should be a Unique Identifier, make yourself a UserID Field, for example with Firebase Auth use firebase.Auth().currentUser.uid as the ID of your User specific saved data in the Firestore.
I Suggest you to Change that in General that solves your Problem and more importantly gives you a solid structure. (The UID from the Auth is Unique)

Retain Dynamically Added DOM Elements when logging out

I recently came across a feature that Salesforce Applications have, i.e. when we log out, the tabs opened during the session are preserved and are displayed again when we log back in at a later point of time.
I would like to implement something similar in my web application where I would like to retain the dynamically created DOM elements so that if I refresh the page or logout, those elements still are displayed unless the end user decides to delete/close/destroy those elements.
Has anyone implemented anything that sounds familiar? If yes, what would be the ideal way to go about it?
Appreciate the help!
I have a webapplication that holds users and adresses as well as various different values. I have implemented a review function as a helper if you go through your data on an infrequent basis. It marks each value as reviewed or not. As this feature is only a helper and a review flag or timestamp is not needed and implemented in the DB, I save an array of data as a JSON string locally using localstorage.
This is enough for my case. You could do the same for your datamodell. You can of course also save this data per user on a separate table in the db. Consider something like: id, userid, featurename, etc.. with this generic layout you can save the state for each feature of your app, be it a tab, a modal, a setting or whatever.
Of course, you need a (preferably JS) function that gets these settings and then can recreate the DOM elements or fetch them via AJAX. You need as well a function that sends an AJAX request to save the information that a feature/window/tab has been opened/closed/etc.
A lot of work for a "nice feature". Might not be a top priority on your bucketlist, but definitly enhances your user experience.
I refresh the page or logout, those elements still are displayed
unless the end user decides to delete/close/destroy those elements.
That can only be possible if before refresh/logout those dynamically created elements are stored.
That can be possible by either storing the value in database or using local/session storage.
Values of the dynamically generated elements can be stored in localStorage like
localStorage.set('someKeyName' ,'value of dynamically generated Elements in string format')
Then after refresh retrieve the values and create those elements and append it to dom

Categories

Resources