[英]How can I conditionally add items to Firestore?
我希望有条件地将项目添加到 Firestore。 在下面的示例中,如果add
为true
,我只想添加code
、 time
和comment
。
await firebase
.firestore()
.collection("codes")
.add({
total,
subtotal,
code: add && code,
time: add && new Date(),
comment: add && comment
});
现在,如果add
是 false code
, time
和comment
将作为 boolean false
附加到 Firestore。 我不想添加任何内容。
您可以简单地使用if
语句包装您的代码并检查codePresent
的值:
if(codePresent) { // or better - if(code) {...
await firebase
.firestore()
.collection("codes")
.add({
total,
code // this is the same as doing { code: code }
});
}
如果您有多个案例并且不想添加一堆 if 语句,则可以简单地根据变量的内容过滤变量:
const payloadOptions = {
foo: "some random data";
code: "function foo() { return 'foo' }";
empty: null;
optionalParameter: null;
}
const filteredPayload = Object
// turning our object into an entry array, i.e [["foo", "some random data"..]]
.entries(payloadOptions)
// if we have a value, we assign it to our accumulator
.reduce((acc, [key, value]) => {
if(value) {
acc[key] = value;
}
}, {});
await firebase
.firestore()
.collection("codes")
.add(filteredPayload);
您可以执行以下操作:
let obj = {}
obj.total = total;
obj.code = codePresent?code : null;
Object.keys(obj).filter((key) => {
obj[key] == null? delete obj[key] : key
});
console.log(obj);
基本上创建一个空的 object,然后添加带有值的键。 关于code
字段,如果codePresent
为 false,则使用三元运算符,然后将其分配给 null。 然后使用Object.key()
将返回一个键数组,然后您可以使用filter()
方法并从 object 中删除值为 null 的键。 最后只需将 object 作为参数传递给add()
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.