How to insert and auto remove filed unnecessary or null in firestore

I am trying some ways to completely delete the filed 1 when it is null when inserting data

For example: I'm 1 user A I have name, age and country is null But I don't want it to add a country field in the database

like this

db.collection("user").doc().set({
    name: "A",
    age: "18",
    country: "" or country: null or country:'null'
}).then(() => {
    console.log("Document successfully written!");
})

I want it like this

Collection(user)=>randomUid=>data(name:'A',age:'18')

Upvotes: 3

Views: 179

Answers (1)

samthecodingman
samthecodingman

Reputation: 26246

You could achieve this using spread syntax and a conditional object.

const country = /* ... value from form/page/etc ... */;

db.collection("user").doc()
  .set({
    name: "A",
    age: "18",
    // if country is truthy and also not "null", include it, otherwise, omit it.
    ...(country && country !== "null" ? { country } : {})
  })
  .then(() => {
    console.log("Document successfully written!");
  })
  .catch(err => console.error) // don't forget to handle errors!

Upvotes: 2

Related Questions