Home > other >  Taking more than 3 minutes to update a Firestore document
Taking more than 3 minutes to update a Firestore document

Time:09-17

A simple update in a Firebase document from a Firebase function (using Firebase admin) is taking more than 3 minutes!

  1. The update is instantaneous using Firebase emulator
  2. The Firestore database has no more than 20 entries in total
  3. The delay happens even in subsequential requests in the same minute (doesn't seem to be a "cold start" issue)
const userData = {
   firstName: "John",
   lastName: "Doe"
}

/***** FROM HERE *****/
functions.logger.log("Updating user", userData)

const usersRef = admin.firestore().collection("users").doc("1")
usersRef.set(userData, { merge: true })
        .then(() => {
              /***** TAKES 3 MINUTES TO GET HERE *****/
              functions.logger.log("Success user updated!", userData)
          })
        .catch((error) => {
              functions.logger.error("Error updating user!", error)
          })

Any help will be much appreciated!

CodePudding user response:

Try this, getting the reference is asyncronous and you are not handling that.

const userData = {
  firstName: 'John',
  lastName: 'Doe',
}

functions.logger.log('Updating user', userData)

admin
  .firestore()
  .collection('users')
  .doc('1')
  .then((usersRef) => {
    usersRef
      .set(userData, { merge: true })
      .then(() => {
        /***** TAKES 3 MINUTES TO GET HERE *****/
        functions.logger.log('Success user updated!', userData)
      })
      .catch((error) => {
        functions.logger.error('Error updating user!', error)
      })
  })

The cleaner (and more reliable) version of this code would be to use async/await and not promise chaining

const cleanFunction = async () => {
  const userData = {
    firstName: 'John',
    lastName: 'Doe',
  }

  functions.logger.log('Updating user', userData)

  try {
    const usersRef = await admin.firestore().collection('users').doc('1')
    await usersRef.set(userData, { merge: true })
    functions.logger.log('Success user updated!', userData)
  } catch (error) {
    functions.logger.error('Error updating user!', error)
  }
}
cleanFunction()
  • Related