【问题标题】:How do I only add the field in an object if the value isn't null? Javascript如果值不为空,如何仅在对象中添加字段? Javascript
【发布时间】:2021-12-05 10:12:03
【问题描述】:

我目前正在使用 mongoose 将数据写入 MongoDB 集合中的文档,但我不接受空字段,我已经在文档中设置了默认值。 我调用了一个更新函数,其中一些字段为空,那些已经为空的字段,我不希望他们进行修改。

例子:

const Business = require("./businessModel") //This references the model
const {id, email, name, contactNumber} = args
const business = await Business.findByIdAndUpdate(
  { id},
  {
   name: ((name != null) ? name : (skip this field))... //HERE
  });

我在这里评论的地方,如果名称不为空,这意味着它存在一个值,那么现在将预定义的模式值名称设置为新名称输入,否则不要更改任何内容并跳过该字段。 我已经有一个替代方案,我首先调用文档,然后将其替换为文档的默认值,但这需要一个我认为不是最佳解决方案的文档调用。

【问题讨论】:

    标签: javascript json mongodb mongoose


    【解决方案1】:

    看起来您的 args 变量是一个具有相关字段的对象。

    您可以只提取id 并保留...rest,而不是解构所有单独的属性。然后,您可以过滤此 rest 对象的空属性。

    // mock
    const args = { id: 1, name: null, email: 'email@domain', contactNumber: 4 };
    
    //const Business = require("./businessModel") //This references the model
    
    const { id, ...rest } = args;
    const update = Object.fromEntries(Object.entries(rest).filter(([, v]) => v != null));
    console.log(update);
    
    //const business = await Business.findByIdAndUpdate({id}, update);

    更多对象属性过滤选项:Remove blank attributes from an Object in Javascript

    注意:NULL 不存在,javascript 中的 null 对象是小写的null。见:why using NULL with logical operator throws error in JS

    【讨论】:

    • 我已编辑并更正了 null。您的解决方案非常完美,非常感谢。
    【解决方案2】:

    尝试使用update-validators。所以在你的情况下,检查name字段=== null中的值,并根据需要处理错误响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      相关资源
      最近更新 更多