Set raw = true on Sequelize Model.create

前端 未结 3 988
青春惊慌失措
青春惊慌失措 2021-02-08 22:26

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

相关标签:
3条回答
  • 2021-02-08 22:32

    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

    0 讨论(0)
  • 2021-02-08 22:45
    Model.create(modelObject)
    .then((resultEntity) => {
        const dataObj = resultEntity.get({plain:true})
    }
    

    Like mentioned before or if you want to keep with async/await syntax go for:

    const myResultVar = (await Model.create(modelObject)).get({plain:true})
    

    Basically the same thing just not leaving the async/await syntax behind :)

    0 讨论(0)
  • 2021-02-08 22:54

    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.

    0 讨论(0)
提交回复
热议问题