Surafel
Surafel

Reputation: 835

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?

Upvotes: 12

Views: 11287

Answers (3)

Sankha Rathnayake
Sankha Rathnayake

Reputation: 843

If in case if there's anyone who didn't have luck with above provided answers,
try this -> docref.set({ 'id':docref.ref.id}).
It worked for me. Below is a usecase of this.

create(tutorial: any): any {
    var docref = this.db.collection('invxxx').doc()
    docref.set({ 'id':docref.ref.id, anotherField: 'anotherValue'});
  }

Upvotes: 0

PicNer
PicNer

Reputation: 11

the previous method works fine but just for the sake of clarification

what is it really like

const { doc, collection, getFirestore, setDoc, addDoc } = require('firebase/firestore');
let collectionId = "Cars";
let docId;
let firestore = getFirestore();



   async function addDocWithId() {
        let collectionRef = collection(firestore, collectionId)
    
        addDoc(collectionRef, {}).then(res => {
            docId = res.id
            let docRef = doc(firestore, collectionId + "/" + docId)
    
            setDoc(docRef, {
                id: docId,
                car: 'Benz'
            })
        })

    };

how it has been clarified

const { doc, collection, getFirestore, setDoc, addDoc } = require('firebase/firestore')
let collectionId = "Cars"

let firestore = getFirestore()
async function addDocWithId() {
    let collectionRef = collection(firestore, collectionId)
    let docRef = doc(collectionRef)

    setDoc(docRef, {
        id: docRef.id,
        car: "Volvo"
    })


}

Upvotes: 0

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

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

Upvotes: 27

Related Questions