首页 > 解决方案 > 图像存储在firestore中,但仍在浏览器中显示firebase错误(不支持的字段值:未定义)?

问题描述

Firebase 错误(未处理的拒绝)

在浏览器上反应错误:

Unhandled Rejection (FirebaseError): Function addDoc() called with invalid data. Unsupported field value: undefined (found in field username in document posts/MkHzQWzXyayty0KfQQgP)

很可能问题出在这段代码中:

                // complete function
                storage
                    .ref("images")
                    .child(image.name)
                    .getDownloadURL()
                    .then(url => {
                        // Post image on db
    
                        db.collection("posts").add({
                            timestamp: firebase.firestore.FieldValue.serverTimestamp(),
                            caption: caption,
                            imageUrl: url,
                            username: username
                        });

                        setProgress(0);
                        setCaption("");
                        setImage(null);
                    });
            }
        );
    }; ```

标签: firebasegoogle-cloud-firestore

解决方案


In the error, it says your variable username is undefined. You should make sure that it has a value. Meanwhile, you can do a quick and dirty fix like this:

    db.collection("posts").add({
        timestamp: firebase.firestore.FieldValue.serverTimestamp(),
        caption: caption,
        imageUrl: url,
        username: username || null,
    });

This code will assign null to username when the variable username is undefined.


推荐阅读