Home > database >  How to get document one time and using it every where
How to get document one time and using it every where

Time:02-01

I using firebase admin and use nodejs get data by phone number from firebase. When i get success , i want get only document one time and use it every time. It possible ?

Picture :

enter image description here

First i get document by phone look like. Example:

const phone = await admin.firestore().collection('users').where('phone_number', '==', phone).get()

After that , i want using document phone every time in my code look like :

await handleLogic(phone)

Then

 async function handleLogic(phone) {
   //inside here i need call await admin.firestore().collection('users').where('phone_number', '==', somePhone).get() or re use phone in parameter ?  
 phone.ref.collection("subcollection").get()
        .then(() => {
            let data = {
                
                created_at: timeNowFirebase(),
            };

            phone.ref.collection(subcollection).doc(someId)
                .set(data);
  }

I have question : Inside function handleLogic(phone), i need re call admin.firestore().collection('users').where('phone_number', '==', phone).get() or only use parameter phone and used phone.ref.collection(subcollection).doc(someId).set(data); . It will set subcollection into document my phone correct ?

CodePudding user response:

Yes you can store the document ID (or even the DocumentReference as you are currently) in memory/cache instead of querying the document with phone number every time. The doc ID never changes and this seems to be a good way to prevent additional requests to the database.

// storing in memory for example
const phoneToUserId = {};

async function handleLogic(phone) {
  if (!phoneToUserId[phone]) {
    // run a query to get userID from phone number
    const user = await admin.firestore().collection('users').where('phone_number', '==', somePhone).get()
    phoneToUserId[phone] = user.docs[0].id
  } 

  // get a reference to sub-collection
  const subCol = admin.firestore().collection(`users/${phoneToUserId[phone]}/subcollection`)
  // query data
}

However do note that you'll have to update that object whenever user updates their phone number or delete their document.

  •  Tags:  
  • Related