首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果值不是null,如何只在对象中添加字段?Javascript

如果值不是null,如何只在对象中添加字段?Javascript
EN

Stack Overflow用户
提问于 2021-10-18 10:39:21
回答 1查看 599关注 0票数 0

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

示例:

代码语言:javascript
复制
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
  });

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-18 11:16:25

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

您可以只提取id并保留...rest,而不是破坏所有单独的属性。然后,可以为空属性筛选这个rest对象。

代码语言:javascript
复制
// 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__。请参阅:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69614650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档