k10a
k10a

Reputation: 1087

'DocumentData | undefined' error occurs on Cloud Function

I tried to change the name of the user saved in the firestore on Cloud Function, but the following error appears and I cannot deploy it.

Property 'name' does not exist on type 'DocumentData | undefined'.

The code is here.

const userDoc = await admin
  .firestore()
  .doc(`users/${uid}`)
  .get()
  .then((userDocSnap) => {
    return userDocSnap
  })
const { name } = userDoc.data()

if (name === 'firstName') {
  userDoc.ref.update({
    name: 'secondName',
  })
}

Sorry, please let me know how I can solve this problem.

Upvotes: 0

Views: 112

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317808

userDoc.data() can return either a DocumentData object, or undefined if no document was found. The error is TypeScript telling you that you're possibly trying to pull the name property from an undefined object, which would crash your program.

What you should do is check to make sure the return value is defined before accessing properties on it:

const userDoc = await admin
  .firestore()
  .doc(`users/${uid}`)
  .get()

const data = userDoc.data()
if (data) {
    const { name } = userDoc.data()
    
    if (name === 'firstName') {
      userDoc.ref.update({
        name: 'secondName',
      })
    }
}
else {
    // decide what you want to do if the document doesn't exist
}

Note that I removed the call to then. It's completely unnecessary here due to the way await works.

Also, it looks like you might be using an very very old version of the Firestore library. DocumentData was replaced with DocumentSnapshot a long time ago.

Upvotes: 2

Related Questions