0

I am creating one of my firsts webs that I intend to launch to the real world using JAMstack with Firestore. I am running into this problem and haven't been able to figure it out after doing days of research. This line is overwritting the data because even when the form camps remain unfilled, they get null values that get pushed to the database. How can I push only the non-null values?

const formData = new FormData(userform);
const image = formData.get('userimage')
const description = formData.get('userdescription')
const facebook = formData.get('facebook')
const instagram = formData.get('instagram')
const twitter = formData.get('twitter')

db.collection('users').doc(firebaseUser.uid).set({description, image, facebook, instagram, twitter},{merge : true});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

0

As Doug commented, you'll have to not pass the keys without a value. When you pass a key with a null value, that's an explicitly instruction to Firestore to set null to that key.

A simple way to do this (thanks to this answer):

const formData = new FormData(userform);
const image = formData.get('userimage')
const description = formData.get('userdescription')
const facebook = formData.get('facebook')
const instagram = formData.get('instagram')
const twitter = formData.get('twitter')

const values = Object.entries({description, image, facebook, instagram, twitter})
    .filter(([name, value]) => value !== null)
    .map(([name, value]) => ({name, value}));

db.collection('users').doc(firebaseUser.uid).set(values, {merge : true});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

Frank and Doug were right. The problem was that Frank's answer returned an array instead of an object. so I used the second answer on this question which was

              Object.keys(myObj).forEach(
                (key) => myObj[key] == "" && delete myObj[key]
              );