【问题标题】:Can I merge data when sending put request to firebase realtime database using axios?使用axios向firebase实时数据库发送put请求时可以合并数据吗?
【发布时间】:2020-07-11 13:00:43
【问题描述】:

我可以像这样使用 axios 更新 Firebase 实时数据库中的数据:

axios.put('/blogposts/' + postId + '.json', post, {headers: {'Content-Type': 'application/json'}}).then(response => {
  res.status(200).send(json.stringify(response.data));
}).catch(err => {
  res.status(500).send('error putting blog post.');
});

但是发布的帖子是这样的:

{
  title: '...',
  body: '...'
}

数据库中的帖子如下所示:

{
  title: '...',
  body: '...',
  createdAt: 123,
  updatedAt: 123
}

在发布帖子之前,我给它一个 updatedAt 标记:

post.updatedAt = Date.now();

然后我使用上面的 axios 调用发布帖子。

在数据库中,帖子最终看起来像这样:

{
  title: '...',
  body: '...',
  updatedAt: 123
}

createdAt 消失了。

我想知道是否有一个配置设置告诉 Firebase 不要覆盖整个帖子,而是一个一个地覆盖每个字段,以便标题被覆盖,正文被覆盖,updateAt 被覆盖,但 createdAt 被单独留下。我相信这被称为合并,但是将 merge:true 添加到配置对象并不能满足我的要求。

有没有办法做我想做的事,或者更新的对象是否总是必须包含旧对象的每个字段,即使该字段没有被更新?

谢谢。

【问题讨论】:

    标签: firebase firebase-realtime-database merge axios put


    【解决方案1】:

    要将您写入的数据与 REST 请求中该位置的现有数据合并,use the PATCH verb。从那里得到这个例子:

    curl -X PATCH -d '{
      "nickname": "Alan The Machine"
    }' 'https://docs-examples.firebaseio.com/rest/saving-data/users/alanisawesome.json'
    

    在 Axios 中似乎转换为 axios.patch(...)

    【讨论】:

    • 谢谢弗兰克。这正是我想要的。
    猜你喜欢
    • 2021-06-03
    • 2018-10-24
    • 2022-06-26
    • 2018-04-24
    • 2020-11-03
    • 1970-01-01
    • 2020-11-27
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多