javascript - 如果值不为空,如何仅在对象中添加字段?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
});
我在这里评论的地方,如果名称不为空,这意味着它存在一个值,那么现在将预定义的模式值名称设置为新的名称输入,否则不要更改任何内容并跳过该字段。我已经有一个替代方法,我首先调用文档,然后用文档的默认值替换它,但这需要一个我认为不是最佳解决方案的文档调用。
解决方案
看起来您的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 和逻辑运算符会引发错误
推荐阅读
- api - Stocktwits API 不工作,错误是“此页面不工作”
- amazon-web-services - 如何使用 AWS CLI 仅列出 AWS 组织下的帐号和账户名称
- javascript - 反应没有为相同的 URL 获取不同的图像
- c# - EF Core 6 派生的 DbContext 未从 Startup 获取连接字符串
- python - python从元组列表中删除tup [0]重复项
- visual-studio-code - (vs代码)杀死终端按钮消失了
- java - 为什么在尝试运行 JavaFX 项目时应用程序启动方法出现异常?
- amazon-web-services - 将 AWS Amplify Web App 部署到 EC2(不是 Lambda)
- javascript - 将单元格编辑为谷歌表格应用程序脚本中的某些文本时如何触发功能?
- flutter - 如何使用 Flutter Google Mobile Ads with provier (MVVM)