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

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)

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}'`))

Firestore doesn't creates parent Document

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.

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.

Is there a possible way to access the latest document which is added to the firestore database?

I need to access the latest document that is added to the database, So that with that refID I can add other field to the same document without overriding other documents.
You can add timestamps of documents when you add them to the database, so when you want to access the latest one, just compare the timestamps.
When pushing you can use Date.now() for this.
If what you want is to add information to documents as they are created, I think a better pattern would be to use a firebase function that triggers on creation of new documents in firestore: https://firebase.google.com/docs/functions/firestore-events
Otherwise, a order by timestamp and limit 1 should do the trick: https://firebase.google.com/docs/firestore/query-data/order-limit-data

Meteor facebook id vs accounts id

I am making an application which uses both the accounts package and facebook's graph api. Specifically the friends api. The friends api returns all facebook friends that have used the application. The problem is that it returns facebook id's, and the accounts package generate application specific id's. This is problematic when i want to retrieve information from a collection containing a friends information, but stored with the application specific id. I have worked around this by storing both the fb id and the accounts id in the collection.
But i still can't update a user data based on their fb id, as update is only permitted using the application specific id. What i want, but not allowed:
UserData.update({fbId: friend.fbId},{$push: {some: data}});
The only solution i could think of is to get each user id first, like this:
var friendId = UserData.findOne({fbId: friend.fbId})._id;
This is obviously not a good solution as it needs one extra db call for every update.
Is there a way of setting the accounts id equal to the facebook id upon creation? Or do you have any other suggestions.
Extending on the comment above:
MoeRum: #Xinzz UserData is a custom collection. If try updating with fbId I get the
following error: Uncaught Error: Not permitted. Untrusted code may
only update documents by ID. [403]
That is because you're trying to update on the client-side. You can only update by ID on the client-side. What you're trying to do should not be a problem as long as you do it on the server.
From the Meteor docs (for more reference: http://docs.meteor.com/#/full/update):
The behavior of update differs depending on whether it is called by
trusted or untrusted code. Trusted code includes server code and
method code. Untrusted code includes client-side code such as event
handlers and a browser's JavaScript console.
Trusted code can modify multiple documents at once by setting multi to
true, and can use an arbitrary Mongo selector to find the documents to
modify. It bypasses any access control rules set up by allow and deny.
The number of affected documents will be returned from the update call
if you don't pass a callback.
Untrusted code can only modify a single document at once, specified by
its _id. The modification is allowed only after checking any
applicable allow and deny rules. The number of affected documents will
be returned to the callback. Untrusted code cannot perform upserts,
except in insecure mode.

Categories

Resources