javascript - 如何在 firestore 中插入和自动删除不必要的或空的

标签 javascript firebase react-native google-cloud-firestore

我正在尝试一些方法来完全删除插入数据时为空的字段1

例如:我是 1 用户 A 我有姓名、年龄和国家/地区为 null 但我不希望它在数据库中添加国家/地区字段

像这样

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

我想要这样

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

最佳答案

您可以使用 spread syntax 实现此目的和一个条件对象。

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!

关于javascript - 如何在 firestore 中插入和自动删除不必要的或空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66764310/

相关文章:

react-native - 如何使用 native 导航来创建嵌套导航? (例如 : Stack navigator inside a Tab navigator)

reactjs - React-Native/Typescript - 未定义不是一个对象(评估'react_1.default.Component)

android - 为什么 32 位 Android 应用可以在 64 位设备上运行?

javascript - 如何允许用户在阻止后启用推送通知?

javascript - 如何匹配 "by"之后的第一个单词

javascript - KnockoutJS 数组

firebase - Firestore社交网络数据结构

javascript - 处理 JavaScript 中未定义的属性

Android Firebase 无法将 java.util.HashMap 类型的值转换为字符串

ios - 从 Firebase 观察者代码块 swift 中的函数返回数据