DEV Community

TK
TK

Posted on

3 1

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay