Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set raw = true on Sequelize Model.create

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

like image 493
Mon Avatar asked Aug 08 '17 08:08

Mon


People also ask

What does raw true do in Sequelize?

Conclusion. In short, this story shared my experience in working with Sequelize raw options, setting raw to true will change your boolean expected field to number, and lastly, we could use a better approach which is toJSON to achieve my desired outcome.

How do I create a raw Sequelize in SQL?

Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );

How do I set default value in Sequelize model?

When you create a Sequelize model, you can add the default value for your model by adding the defaultValue option to the column(s) definition. The defaultValue option will be used by Sequelize to define default value(s) for your SQL column(s) when you create a table using Sequelize.

What is the use of sync true and sync false option in Sequelize?

User.sync({ alter: true }) - This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.


1 Answers

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.

like image 142
Mon Avatar answered Sep 18 '22 20:09

Mon