Set raw = true on Sequelize Model.create

試著忘記壹切 提交于 2019-12-05 02:13:58

问题


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.

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

Thanks


回答1:


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.

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})
}

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

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.

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.

Thank you very much.




回答2:


You can also use .toJSON() on the model instance that's returned from the query. http://docs.sequelizejs.com/class/lib/model.js~Model.html#instance-method-toJSON



来源:https://stackoverflow.com/questions/45563842/set-raw-true-on-sequelize-model-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!