firebase / firebase/firebase-js-sdk

serverTimestamp() not working inside FirestoreDataConverter

Open
#6,313 5 comments 0 reactions 1 assignee Claimed by @wu-hui View on GitHub
api: firestore needs-attention v9
Dominant language
TypeScript
Stars
5.1k
Forks
1k
Avg merge
2d 21h
Merged PRs (30d)
37

Description

### [REQUIRED] Describe your environment

* Operating System version: macOS 12.3.1 (Monterrey) on M1 Pro
* Browser version: Node v16.14.2
* Firebase SDK version: ^9.8.2
* Firebase Product: Firestore (auth, database, storage, etc)

### [REQUIRED] Describe the problem

#### Steps to reproduce:

I am using `FirestoreDataConverter`s to map to my custom types. One object type, called "CompanyProduct" contains a "created_at" field.

My converter takes the given object and if does not find a created_art defined, adds a timestamp to it. If I add a `new Date()` to my "create_at" field it works fine, but using `serverTimestamp() ` (as it should be done), the code fails with the following error:

```
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^

[FirebaseError: Function WriteBatch.set() called with invalid data (via `toFirestore()`). Unsupported field value: a custom ServerTimestampFieldValueImpl object (found in field created_at in document products/P1I6ugb29rzcOVEcbjEK)] {
code: 'invalid-argument',
customData: undefined,
toString: [Function (anonymous)]
}
```

#### Relevant Code:

Product interface
```typescript
export interface CompanyProduct {
id?: string;
created_at?: Date;
...
}
```

Converter
```typescript
export const ProductConverter: FirestoreDataConverter = {
toFirestore(product: WithFieldValue< CompanyProduct >): DocumentData {

let newProduct = product;

if (newProduct.created_at != undefined) {
newProduct.created_at = newProduct.created_at
} else {
newProduct.created_at = serverTimestamp()
}

return newProduct;
},
fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): CompanyProduct {
const data = snapshot.data(options);
data.id = snapshot.id
return data as CompanyProduct;
},
};

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.