Home > database >  Better way to get document ID which was auto generated to create the doc or update an array inside t
Better way to get document ID which was auto generated to create the doc or update an array inside t

Time:12-08

I'm creating one document per user to store the id's of the users bookmarks. I'm using addDoc so the ID of the created doc is generated by firebase. I want to check if that document exists to create a new one or update the old. I need to have a document reference to update the doc and I had a horrible time trying to figure out a way to get a hold of that auto generated ID. My code works but it feels really hacky - Is there a better way to accomplish this?

//Add a value to the bookmarks array for individual user
export const addBookmarkForUser = async (userAuth, showId) => {
  const bookmarkDocRef = collection(db, 'users', userAuth.uid, 'bookmarks')
  const bookmarkSnapshot = await getDocs(bookmarkDocRef)
  let userBookmarkDocId
  if(bookmarkSnapshot){   
    bookmarkSnapshot.forEach((doc) => {
      if(doc.id){
        userBookmarkDocId = doc.id
        console.log(userBookmarkDocId)
      }
    })    
  }  
  try {    
    if(!bookmarkSnapshot) {
      await addDoc((collection(db, 'users', userAuth.uid, 'bookmarks'), {
        favorites: [{showId: showId}],
      }))
    }else {
      const userBookmarkRef = doc(db, 'users', userAuth.uid, 'bookmarks', userBookmarkDocId)
      await updateDoc(userBookmarkRef, {
        favorites: arrayUnion({showId: showId})
      })}
    
  } catch (error) {
    console.log('Error creating bookmark', error.message);
  }
};

I know I will only have one document in there for each user - is there a better way to find the doc.id?

Here is the firestore structure - firestore1

firestore2

CodePudding user response:

If you just want to check how many documents are present in a collection then you can use getCountFromServer() that loads the count without the actual document data.

import { collection, getCountFromServer } from 'firebase/firestore';

const bookmarkColRef = collection(db, 'users', userAuth.uid, 'bookmarks');
const bookmarksCount = (await getCountFromServer(bookmarksColRef)).data().count

console.log(`${bookmarksCount} documents found in ${bookmarksColRef.path}`)\

if (!bookmarksCount) {
  // no document exists, create new 
}

However, since you need the document ID and its data. You can run a simple query:

import { collection, getDocs } from 'firebase/firestore';

const bookmarkColRef = collection(db, 'users', userAuth.uid, 'bookmarks');
const bookmarksSnap = await getDocs(bookmarksColRef);

if (bookmarksSnap.empty()) {
  // no document
} else {
  const docData = bookmarksSnap.docs[0].data();
  console.log(docData)
}
  • Related