首页 > 解决方案 > 如果值不为空,如何仅在对象中添加字段?Javascript

问题描述

我目前正在使用 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
  });

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

标签: javascriptjsonmongodbmongoose

解决方案


看起来您的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。请参阅:为什么在 JS 中使用 NULL 和逻辑运算符会引发错误


推荐阅读