考虑方法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.
答案 0 :(得分:2)
只需传递一个带有字段名称和值的对象即可更新。
txn.update(docRef, {
field1: value1,
field2: value2
})
在TypeScript中,{[fieldPath: string]: any}
的意思是“对象的属性必须是字符串,并且其值可以是任何值”。在这种情况下,它们的键是要更新的字段的路径。