How can I use node -orm2 to model two or more databases using Express?

I am trying to use node-orm2 as middleware with Express, the documentation only shows how you can connect to only one database.

I tried to get Express to use two different layers of the middleware, but no luck. For instance,

app.use(orm.express('sqlite://test.db', define: { /* define table1 */ })); app.use(orm.express('sqlite://test2.db', define: { /* define table2 */ })); 

I directed everything correctly to this get handler:

 app.get("/", function (req, res) { var t1 = req.db.models.table1.find(...); var t2 = req.db.models.table2.find(...); res.send([t1,t2]); }); 

Since the first base is app.use d table1 , the second of find invocations will give

 TypeError: Cannot call method 'find' of undefined 

... this means that the two define: blocks were not merged, which we would like.

How do I access two databases using node -orm2?

+4
source share
1 answer

Your code seems beautiful. I think the problem is that you are using "req.db.models" instead of "req.models". From the doc:

 app.get("/", function (req, res) { // req.models is a reference to models used above in define() req.models.person.find(...); }); 

And:

You can call orm.express several times to have multiple database connections. Models defined in all joins will be merged into req.models . Remember to use it before app.use (app.router), preferably right after your public asset folders (s).

Everything is simply combined under the β€œmodels”, there are no differences between the databases. This means that you cannot name your models the same for multiple databases, but c'est la guerre.

+1
source

Source: https://habr.com/ru/post/1469277/


All Articles