Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 214
iSaumya Avatar asked Aug 31 '18 11:08

iSaumya


People also ask

Can I change document ID in firestore?

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.

Is there any way to update a specific index from the array in firestore?

No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.


2 Answers

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:

  1. Read the document from its existing key.
  2. Write the document under its new key.
  3. Delete the document under its old key.

You'll want to run these operations in a transaction, to ensure the operations complete atomically.

like image 115
Frank van Puffelen Avatar answered Oct 17 '22 20:10

Frank van Puffelen


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)

like image 6
Badgy Avatar answered Oct 17 '22 20:10

Badgy