本文介绍了在 Sequelize Model.create 上设置 raw = true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在 Sequelize 上调用 Model.create 后能够接收纯原始对象,即创建的对象本身,没有元数据或任何其他内容.就像 Model.find 中的 {raw: true} 选项一样.

I want to be able to receive the plain raw object after calling Model.create on Sequelize, the object itself that was created, no metadata or any other things. Just like the {raw: true} option in Model.find.

我已经看到了这个答案:将所有查询设置为 raw = true sequelize,不,Model.create({name: 'test'}, {raw: true}) 不起作用.

I've already seen this answer:Setting all queries to raw = true sequelize,and no, Model.create({name: 'test'}, {raw: true}) doesn't work.

谢谢

推荐答案

非常感谢您的帮助.我找到了一个解决方案,虽然这不是我想要的,但它有效,而且仍然很好.

Thank you very much for your help. I found a solution, though this isn't exactly what I'm looking for, but it works, and also still good.

sequelize 实体有一个 .get() 方法来返回纯对象版本.所以它是这样的:

The sequelize entity has a .get() method to return the plain object version. So it goes something like this:

Model.create(modelObject)
.then((resultEntity) => {
    const dataObj = resultEntity.get({plain:true})
}

来自此线程:续集,将实体转换为普通对象.寻找 CharlesA 的答案.

Coming from this thread: Sequelize, convert entity to plain object. Look for CharlesA's answer.

尚未尝试使用数组,但如果您对数组结果有疑问,请查看其注释和旁边的答案.但是由于 .create() 只返回一个对象,它对我有用.无论如何,如果您使用 .findAll(),则应该使用 {raw: true} 选项而不是此解决方案,因为它适用于该方法.

Haven't tried with arrays but check its comments and the answer next to it if you're having problems with array of results.But since .create() only returns an object, it works for me. Anyway if you are using .findAll(), you should use {raw: true} option instead of this solution because it works in that method.

附:如果有人仍然有一个解决方案,其中 Sequelize 本身不会返回那个大的 resultEntity 对象,而只是简单的数据对象,就像 {raw: true} 选项一样(因为我认为这仍然更轻?),我们'是开放的.

P.S. If anyone still has a solution where Sequelize itself will not return that large resultEntity object, but just the plain data object, just like {raw: true} option (because I think that's still lighter?), we're open.

非常感谢.

这篇关于在 Sequelize Model.create 上设置 raw = true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:03