Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include the document id as a field id in firestore

Heres what i am trying to achieve i want a unique id field for every document in my database and i want that unique id to the same as the document id.

Example:

documents:       data:

eBgdTRE123       id:'eBgdTRE123'
                 name:'Jhon Doe'
                 job:'Programmer'     

i want i databse to have this structure, now i got two ideas to achieve this

1: to use cloud function and have onCreate listener and everytime theres a new document grab document and set the id field and update it heres how i am doing it

exports.addDocIdToField = 

functions.firestore.document('collectionname/{docID}').onCreate((snap,context) => {
    const id = context.params.docID;
    return admin.firestore().collection('collectionname')
        .doc(id).set({ id: snap.id }, { merge: true })
        .then(() => {
            return null;
        })
        .catch((error) => {
            return null;
        });
})

2: to use the above kind of method on document creation. add a new document as soon as that document is added get the newly added document and update its id

both of them work but my question is can i rely on this kind of operation? i mean if the id is by any means undefined it can cause an error further in the app.

or if there are other ways to achieve this?

like image 903
Surafel Avatar asked Jan 20 '20 12:01

Surafel


People also ask

How do you store a document ID in a field in firestore?

Map map = new HashMap<>(); map. put("username", username); map. put("email", email); map. put("id", id);

How do I get the document ID added to firestore?

When you call the . add method on a collection, a DocumentReference object is returned. DocumentReference has the id field, so you can get the id after the document was created. // Add a new document with a generated id.

Can documents have the same ID firebase?

The names of documents within a collection are unique.

How do I add a field in firestore?

Build a DocumentReference to the document you want to update, then use the update() method on the DocumentReference to indicate only the fields to be added or changed. Pass it an object with only properties that match the fields to add or change. This user is second on the weekly Google Cloud leaderboard.


1 Answers

See JS SDK v9 syntax at the bottom

There is a simpler way to achieve that, using the doc() method, as follows (here with the JavaScript SDK v8)

var newDocRef = db.collection('collectionname').doc();
newDocRef.set({
                 name:'Jhon Doe',
                 job:'Programmer',
                 id: newDocRef.id
          })

As explained in the doc:

(the doc() method) gets a DocumentReference for the document within the collection at the specified path. If no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference.


You will find similar methods in the other Client SDKs, here for Android and here for iOS.


UPDATE FOR JS SDK v9:

import { collection, doc, setDoc } from "firebase/firestore"; 

const newDocRef = doc(collection(db, "collectionname"));
await setDoc(
       newDocRef, 
       {
         name:'Jhon Doe',
         job:'Programmer',
         id: newDocRef.id
       }
   )
like image 198
Renaud Tarnec Avatar answered Oct 21 '22 06:10

Renaud Tarnec