DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
T-Kisaku
T-Kisaku

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)

This post blew up on DEV in 2020:

js visualized

๐Ÿš€โš™๏ธ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! ๐Ÿฅณ

Happy coding!