Skip to content
Advertisement

How to get users document id in Firestore using Javascript?

how to get only the last document id in Firestore?

i tried

                    auth.onAuthStateChanged(user => {
                //set document from firestore
                    var date=new Date();  
                    var day=date.getDate();  
                    var month=date.getMonth()+1;  
                    var year=date.getFullYear(); 
                    if (user){
                        db.collection('users').doc(user.uid).collection('orders').doc().set({
                            things:cart,
                            orderState: "Order pending",
                            date:day+'/'+month+'/'+year,    
                        })
                        //get document from firestore
             db.collection('users').doc(user.uid).collection('orders').doc().get()
             .then(snapshot => console.log(snapshot.id))
     })

the result i’m getting wrong id thats not in the orders document!!

enter image description here

This is my documents :

enter image description here

Advertisement

Answer

You are running db.collection('users').doc(user.uid).collection('orders').doc() twice which creates 2 different DocumentReferences and hence they are different. If you are trying to get the document that you just added try this:

if (user) {
  db.collection('users').doc(user.uid).collection('orders').doc().set({
    things:cart,
    orderState: "Order pending",
    date:day+'/'+month+'/'+year,    
  }).then((ref) => {
    console.log(ref.id)
    // ref.get() get document
  })  
}   
const ref = db.collection('users').doc(user.uid).collection('orders').doc()
console.log("Doc ID:", ref.id)
ref.set({...data}).then((snapshot) => {
  console.log(`Document ${snapshot.id} added`)
  // This ID will be same as ref.id
})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement