【问题标题】:How to call Transaction.update using strongly typed UpdateData type如何使用强类型 UpdateData 类型调用 Transaction.update
【发布时间】:2023-03-26 14:55:01
【问题描述】:

考虑方法update(documentRef, dataOrField, …preconditionOrValues) → {Transaction}

我需要能够传递多对 (FieldPath, Value),因为我需要一次更新几个字段。可以这样写:

txn.update(docRef,
  'field1', value1,
  'field2', value2
);

Typescript 提供 UpdateData 类型:

  /**
   * Update data (for use with `DocumentReference.update()`) consists of field
   * paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
   * reference nested fields within the document.
   */
  export type UpdateData = {[fieldPath: string]: any};

updateData method signature 被声明为:

    /**
     * Updates fields in the document referred to by the provided
     * `DocumentReference`. The update will fail if applied to a document that
     * does not exist.
     *
     * Nested fields can be updated by providing dot-separated field path
     * strings.
     *
     * @param documentRef A reference to the document to be updated.
     * @param data An object containing the fields and values with which to
     * update the document.
     * @param precondition A Precondition to enforce on this update.
     * @return This `Transaction` instance. Used for chaining method calls.
     */
    update(documentRef: DocumentReference<any>, data: UpdateData,
           precondition?: Precondition): Transaction;

现在,假设我有一堆字段更新,例如:

  const fieldUpdates: FirebaseFirestore.UpdateData[] = [
    { ['field1']: value1 },
    { ['field2']: value2 },
  ];

如何将其传递给update 方法?如下:

txn.update(docRef, ...fieldUpdates);

失败:

Expected at least 2 arguments, but got 1 or more.ts(2557)
firestore.d.ts(378, 49): An argument for 'data' was not provided.

【问题讨论】:

    标签: typescript google-cloud-firestore


    【解决方案1】:

    只需传递一个对象,其中包含要更新的字段的名称和值。

    txn.update(docRef, {
        field1: value1,
        field2: value2
    })
    

    在 TypeScript 中,{[fieldPath: string]: any} 的意思是“一个对象,其属性必须是字符串,并且它们的值可以是任何东西”。在这种情况下,它们的键是要更新的字段的路径。

    【讨论】:

    • 我需要强调的是,我的fieldUpdates 实际上是一个动态列表的更新。换句话说,我并没有真正传递你所描述的常量结构。
    • 然后动态构建你的更新对象。 API 不在乎你是怎么做的。您在此处和文档中看到的内容是为了简单起见,以说明 API 的工作原理。
    • 我刚刚明白了!现在我让它工作了。谢谢你的澄清。
    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 2016-10-20
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    相关资源
    最近更新 更多