DEV Community

TK
TK

Posted on

Firestore error: Error: Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.

Hello!!
I'm trying to use firestore as database of my service api. But it was occured error like below.

Error: Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object.
Enter fullscreen mode Exit fullscreen mode

Approach


import { DocumentData, FirestoreDataConverter, QueryDocumentSnapshot } from '@google-cloud/firestore'

export const converter = <
    AppValue extends object
>(validator?: (value: AppValue) => AppValue): FirestoreDataConverter<AppValue> => {
    return {
        fromFirestore: (snapshot: QueryDocumentSnapshot<AppValue>) => {
            let data = snapshot.data()
            Object.keys(data).forEach((key) => {
                // @ts-ignore
                if (typeof data[key].toDate == "function" && typeof data[key].seconds == "number") {
                    // Timestamp型は扱いにくいのでDate型に強制変更
                    // @ts-ignore
                    data[key] = data[key].toDate()
                }
            })
            return data
        },
        /*
        * Async Await syntax don't support!!
        *
        * Fix like below
        * toFirestore: (value: AppValue): DocumentData => {
        **/
        async toFirestore: (value: AppValue): DocumentData => {
            if (validator) {
                return validator(value)
            }
            return value
        }
    }
}

export default converter

Enter fullscreen mode Exit fullscreen mode

Top comments (0)