繁体   English   中英

如何有条件地将项目添加到 Firestore?

[英]How can I conditionally add items to Firestore?

我希望有条件地将项目添加到 Firestore。 在下面的示例中,如果addtrue ,我只想添加codetimecomment

await firebase
   .firestore()
   .collection("codes")
   .add({
      total,
      subtotal,
      code: add && code,
      time: add && new Date(),
      comment: add && comment
   });

现在,如果add是 false codetimecomment将作为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM