NodeJS Sequelize INSERT处理有时将NULL值作为属性的对象

r3i60tvu  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(173)

我正在尝试使用Sequelize ORM向Postgres数据库插入多个对象。这些对象是从另一个我个人无法更改或修改的项目中获得的。这些对象将具有包含对象的属性。示例对象:

{
id:1,
name:'foo',
created:{user:{'insertattributehere'},date:'insertdatehere'},
modify:{user:{'insertattributehere'},date:'insertdatehere'},
}

为了简单起见,我创建了一个表,其中对象的每个属性都是一列,列的数据类型为String(id为string,name为string,created_user_attribute,created_date等)。

const new_user = await ClassName.create({id: object.id, name: object.name, created_user_attribute: object.user.attribute ...})

但是,有时包含另一个对象的属性可以为空,例如

{
id:2,
name:'bar',
created:{date:'insertdatehere'}, notice that created doesnt have attribute User
modify:{user:{'insertattributehere'},date:'insertdatehere'},
}

这将导致TypeError,因为“created”没有“user”属性。我想要的是一个方法,以某种方式处理这个TypeError,并插入一个NULL值(或“”字符串)
作为最后的手段,我可以手动检查每个属性的空值来处理TypeError,然后创建一个嵌套语句,这样我将插入一个无值字符串,但是,这看起来非常重复和不优雅。
有没有更好的方法来处理这个问题?请注意,我无法更改要插入到数据库中的对象。

jaxagkaj

jaxagkaj1#

你可以使用lodash函数omitBy沿着可选的链接操作符来只获取定义的props,如果省略的props在DB中没有默认值,它们将默认为空值:

const new_user = await ClassName.create(
  _.omitBy({
    id: object.id,
    name: object.name,
    created_user_attribute: object.user?.attribute
  }, _.isUndefined)
)

相关问题