Hessuew
Hessuew

Reputation: 783

Firebase Firestore v9 best practices: ignoreUndefinedProperties vs. conditional addDoc/updateDoc

Hey I just updated my project to use Firebase version 9 modular. Now after refactoring code I'm wondering which way is to get desired outcome:
There is a document that has couple required fields (lets say: name, lastName). Now I want to add/update that document but it has multiple fields that are not required.

What are the best practices to achieve this? To conditionally add/update [1] or to use "ignoreUndefinedProperties" [2]?

[1] conditional add/update...

if(address){
  await updateDoc(
    doc(db, collection, id), {
      name,
      lastName,
      address,
    })
} else {
  await updateDoc(
    doc(db, collection, id), {
      name,
      lastName,
    })
}

[2] ignoreUndefinedProperties...

Also I couldn't find documentation about how to use "ignoreUndefinedProperties" in the new version so could someone guide me to right usage.

EDIT (Also is this (adding EDIT) best way to continue and fine down my question? I'm newbie so I'm looking also for StackOverflow best practices)

I'm testing required values but how should I do with values that are not required?
I have multiple collections and +20 calls to them and in many only 2-4 values are required while there might be 20 unrequired values.
This way I get the following error if any of those unrequired values are undefined and in updateDoc()...

Function updateDoc() called with invalid data. Unsupported field value: undefined (found in field exampleNotRequiredValue in document ...)

So for this case is it better to
[1] check if values are not undefined and in that case add them to update object
[2] use ignoreUndefinedProperties (as isn't this the point of this setting doesn't this do this check automatically and I don't need to change many functions?)

Upvotes: 1

Views: 2591

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50920

"ignoreUndefinedProperties" may not be the best option. If name is required but is undefined for any reason, then it won't be written to the document. You can write security rules that'll check if name and nickname fields are present but it'll be best to conditionally add fields to your update object and make sure the required fields are present.

In case you want to use ignoreUndefinedProperties, you would have to use initializeFirestore instead of getFirestore:

import { initializeFirestore } from "firebase/firestore"

const db = initializeFirestore(app, {ignoreUndefinedProperties: true})

Upvotes: 8

Related Questions