【问题标题】:How to update the only changed fields in Firestore?如何更新 Firestore 中唯一更改的字段?
【发布时间】:2022-01-08 14:45:25
【问题描述】:

在 Firestore 的 users 集合中,我将所有用户的 uid 作为文档,在每个用户文档中我存储用户首选项。

例如,这是我保存在特定用户文档中的用户偏好示例:

{
  "preferences": {
    "settings": {
      "themeColorMode": "light-mode",
      "debugMode": false
    },
    "filterChips": {
      "pathName": {
        "filterChipsPreferences": true
      }
    }
  }
}

我想用 API 正文中发送的数据更新用户文档

我希望该 API 以某种方式兼容

  • 我应该能够添加除首选项之外的另一个根节点
  • 我应该可以在preferences.settings & preferences.filterChips 中自定义和添加新节点
  • 我应该能够更新特定节点 - 示例:preferences.settings.themeColorMode& preferences.filterChips.filterChipsPreferences

例如,在请求正文中我发送此信息:

{
  "preferences": {
    "settings": {
      "themeColorMode": "dark-mode",
      "isSoundNotificationOn": false,
      "isAppListeningToStream": true
    },
    "filterChips": {
      "pathName": {
        "filterChipsPreferences": false
      },
      "FirstUsedSearch": "23/12/2021"
    },
    "columnDefs": {
      "pathName": {
        "ColumnDefsPreferences": true
      }
  },
  },
  "search": {
      "savedSearches":["searchName"]
    }
}

我希望这个结果保存在用户的文档中

{
  "preferences": {
    "settings": {
      "themeColorMode": "dark-mode",
      "isSoundNotificationOn": false,
      "isAppListeningToStream": true,
      "debugMode": false
    },
    "filterChips": {
      "pathName": {
        "filterChipsPreferences": false
      },
      "FirstUsedSearch": "23/12/2021"
    },
    "columnDefs": {
      "pathName": {
        "ColumnDefsPreferences": true
      }
  },
  "search": {
      "savedSearches":["searchName"]
    }
  }
}

我该如何处理?

【问题讨论】:

  • 您真的想构建自己的 API 来接收有效负载然后连接到 Firestore?或者您已经准备好/可以使用标准的 JavaScript SDK?
  • @RenaudTarnec 它必须是一个 API,它从前端用户接收有效负载并将其提供给将连接到 Firestore 的服务器以实现上述几点,你认为这可能吗?跨度>
  • 当然可以。但是哪种服务器会连接到 Firestore?您可以在此服务器上使用什么语言?应该可以在此服务器上使用 Admin SDK 提供的服务器库之一。
  • @RenaudTarnec 我正在使用 typescript 作为一种语言,是的,我正在使用 Firebase Admin SDK
  • 好的,我会写一个anwser。

标签: node.js google-cloud-firestore firebase-admin


【解决方案1】:

由于您在调用 Firestore 的服务器上使用 Node.js Admin SDK,实际上非常简单:您需要使用 DocumentReferenceupdate() 方法。

update() 方法接受具有编码字段路径的对象 作为编码为值的键和字段值,或可变数量的 在字段路径和字段值之间交替的参数。

更准确地说:

// 1/ Define your DocumentReference
const userId  = ...;
const docRef = admin.firestore().doc(`users/${userId}`);

// 2/ Get the desired elements from the payload received by your API and use them to build the object to pass to the update method

// For example

const updateObj = {
    preferences.settings.debugMode: false,
    preferences.settings.themeColorMode: "myColor",
    preferences.filterChips.filterChipsPreferences: "myPref",
    aNewRootNode: {
       foo: 'bar',
       bar: 'foo'
    }
}

await docRef.update(updateObj);

有关如何更新嵌套对象中的字段的更多信息,请参阅doc of the JS SDK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多