【问题标题】:How to roll back an operation in cloud firestore?如何回滚 Cloud Firestore 中的操作?
【发布时间】:2022-03-11 23:58:48
【问题描述】:

我创建了一个云函数来更新我数据库中文档中的一个字段。但是我的实际值被替换为 NaN 我知道这个链接是什么 Cloud function is writing NaN to firestore 。但是我想回滚操作,以便字段恢复它的值。这怎么可能?

【问题讨论】:

  • 在尝试写入之前,您能否检查该值是否为数字?也许您可以在您的问题中添加一些示例代码。
  • 是的,它是一个数字。
  • @JasonBerryman ,让我们认为它不是一个数字,并且在操作后将值替换为 NaN,因为我意识到错误我想将操作回滚到其原始值。

标签: google-cloud-firestore google-cloud-functions


【解决方案1】:

您可以尝试编写新的更新。如果成功,您的.then 可以解决承诺并且函数可以结束。如果失败,请在.catch 中添加几行以使用change.before.data() 更新文档

然后文档将恢复到之前的值。

这里是一些示例代码

const admin = require('firebase-admin');
const functions = require('firebase-functions');

admin.initializeApp();

const firestore = admin.firestore();

exports.myFunction = functions.firestore
  .document('myCollection/{myDocumentId}')
  .onUpdate((change, context) => {

  const newValue = change.after.data();
  const oldValue = change.before.data();
  
  let myChanges = {
    // Update a value
  };
  
  return change.after.ref.update(myChanges)
    .then(() => {
      console.log('Document updated successfully');
      return Promise.resolve();
    })
    .catch(() => {
      // The update failed and the document needs to be rolled back
      return change.before.ref.set(oldValue);
    })
    .then(() => {
      console.log('Document was rolled back');
      return Promise.resolve();
    })
    .catch(err => {
      console.error(err);
      return Promise.reject(err);
    });
});

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 2020-02-02
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多