Kur*_*usu 3 javascript json firebase firebase-realtime-database
我的Web应用程序中有一个简单的表单,它将JSON对象持久保存到Firebase数据库.并非此表单上的每个字段都是必需的,因此在构造发送的对象时,它可能具有多个undefined属性.
由于Firebase在尝试持久化undefined值时会抛出错误(更不用说,你不应该undefined在JSON对象上有一个值),我想知道框架是否提供了任何方法来覆盖所有未定义的值,null甚至是空字符串; 我还没有在网上找到解决方案.
最糟糕的情况我可以null手动设置所有未定义的属性,但我宁愿不这样做
对此有何想法或建议?
非常感谢!
gus*_*pch 18
对于使用 Firestore 的用户,现在可以忽略undefined字段:https : //github.com/googleapis/nodejs-firestore/issues/1031#issuecomment-636308604
elmasry:截至 2020 年 5 月 29 日,Firebase 添加了对使用 { ignoreUndefinedProperties: true } 调用 FirebaseFiresore.settings 的支持。设置此参数后,Cloud Firestore 会忽略对象内未定义的属性,而不是拒绝 API 调用。
例子:
firebase.firestore().settings({
ignoreUndefinedProperties: true,
})
await firebase
.firestore()
.collection('products')
.doc(productId)
.update({
name: undefined, // Won't throw an error
})
Run Code Online (Sandbox Code Playgroud)
我的解决方案是简单地stringify()将对象与a组合replacer以替换所有未定义的值
obj = JSON.parse(JSON.stringify(obj, function(k, v) {
if (v === undefined) { return null; } return v;
}));
Run Code Online (Sandbox Code Playgroud)
然后我将它转换回JSON对象 parse()
从 Firebase 9 JS SDK 的重大变化来看,它可以这样写:
import {initializeApp} from 'firebase/app';
import {
initializeFirestore,
} from 'firebase/firestore/lite';
export const FirebaseConfig = {
apiKey: 'example',
authDomain: 'example.firebaseapp.com',
projectId: 'example',
storageBucket: 'example.appspot.com',
messagingSenderId: 'example',
appId: 'example',
measurementId: 'example',
};
const app = initializeApp(FirebaseConfig);
initializeFirestore(app, {
ignoreUndefinedProperties: true,
});
Run Code Online (Sandbox Code Playgroud)
我不认为有任何特定的方法可以实现这一点,因为 JSON 的性质期望传入一个值,在本例中该值可能是“null”或空字符串。
尽管目前这可能很不幸,但我认为最好在客户端处理这个问题,并在没有输入数据的情况下手动添加“null”或空字符串。然后,您可以稍后使用“ snapshot.val() !== null ”之类的方法在 Firebase 中的该位置测试数据。
| 归档时间: |
|
| 查看次数: |
1720 次 |
| 最近记录: |