Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize - can models be defined multiple times? Can I call sync multiple times?

Tags:

sequelize.js

I have a few questions about the lifetime of a sequelize object

  1. After you create a new instance and authenticate, what happens if the connection drops? How to handle?

  2. I can define a model by calling sequelize.define(). Can it be done multiple times? Can I redefine User on the fly? What happens to existing instances?

  3. Since I have to call sequelize.sync() to synchronize the database, I'm interested if it is ok to call it multiple times.

Thank you

like image 405
Madd0g Avatar asked Sep 30 '22 18:09

Madd0g


1 Answers

  1. I believe connections are made at the time the request occurs. Sequelize does not "keep open" a connection to the database. If the connection drops and comes back, and a query was issued during that time there cannot be a connection, the query will fail. I think i would spend time solving the database reliability issue rather than try other options that mean more code, but that is my opinion.

  2. You should think of define() as a way to set up tables on the db on a dev box during your application startup. Ideally, define should only ever be done once. You can call define as many times as you like, though, but I believe the table state would be "last define call wins". depending on your configuration, define will do a DROP/CREATE of your table, too, so you want to make sure you understand when and why define gets called.

  3. You have to call sync in order to persist your definitions or ensure they are present in the existing db. you most definitely do not want to call it multiple times, and your reference to the sequelize instance should be a singleton.

Of course, you can do whatever you want in dev, but in terms of running sequelize in a production-like setting, you probably don't want sync to run ANY defines, and instead just validate that the model it is expecting that exists in the defines matches the existing schema, and sync should only be called once, ever, and its result should be used as the singleton instance.

like image 166
sanimalp Avatar answered Oct 07 '22 19:10

sanimalp