Define models to be used across multiple databases
Sorry if this doesn't belong here but I am having an issue to re-use models across multiple databases. I think this is related to sequelize-typescript.
When I define my model I am able to add it to a sequelize instance, but when I add it to another instance it fails.
Hey @kartsims, you could use the respositoryMode for that. This mode lets you re-use your models. See https://github.com/RobinBuschmann/sequelize-typescript#how-to-enable-repository-mode for details.
@RobinBuschmann hey awesome work man. Just got a question here as well. I found out how to create / find using repository mode, but how to do updates and deletes? Can I please have some examples? As sequelize static update/delete are all for bulk operations. Thanks.
Hey @kangzj , save and update should still work on your instances (instance.save();) So the created objects are still active records.
Otherwise you have to do it like you said: Using repository.update/delete like so:
await MyModel.update(instance.toJSON(), {where: {id: instance.id}});
Hope this helps.
Still on the topic of the re-use models / repository mode: My understanding (and it seems to work in practice) is the following.
const myRepo1 = sequelizeConnection1.getRepository(MyModel); const myRepo2 = sequelizeConnection2.getRepository(MyModel);
Now when I do something like myRepo1.findAll() the data is distinct from myRepo2.findAll() according to the respective databases that are connected to the instances of sequelize above.
Now, I was wondering, how to protect against someone writing this code in the repository mode: MyModel.findAll() ?? not using the repository but the Model directly... Not sure where the data would be sourced for this? or if it would work?
... AAAhhh - clever: With respect to my own question above, I did a test (MyModel.findAll() ), and got the following error. "Error: Model not initialized: Member "findAll" cannot be called. "MyModel" needs to be added to a Sequelize instance." In repository mode, the models that were defined previously, no longer respond, as don't appear to be registered with the sequelize instance.
Still on the topic of the re-use models / repository mode: (Maybe I get to answer my own question again ;))
Can transactions be used with the repository model. So far, did not have much luck. Is there a trick?
Can transactions be used with the repository model. So far, did not have much luck. Is there a trick?
Start the transaction using the sequelizeConnection object rather than the repository instance.
That's the trick - THANK YOU.