Reputation: 4911
I'm trying to use node-orm2 as middleware with Express the documentation only shows how you can connect to one database only.
I have tried getting Express to use two different middleware layers, 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've routed 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 I app.use
d table1
's database first, the second of the find
invocations will yield
TypeError: Cannot call method 'find' of undefined
... which means that the two define:
blocks haven't been merged, which is what we'd like.
How would I access two databases with node-orm2?
Upvotes: 4
Views: 1262
Reputation: 166
Your code seems fine. I think the problem is that you're using "req.db.models" instead of just "req.models". From the documentation:
app.get("/", function (req, res) {
// req.models is a reference to models used above in define()
req.models.person.find(...);
});
And also:
You can call orm.express more than once to have multiple database connections. Models defined across connections will be joined together in req.models. Don't forget to use it before app.use(app.router), preferably right after your assets public folder(s).
Everything just gets mushed together under "models," there's no differentiator between databases. This means you can't name your models the same thing across multiple DBs, but c'est la guerre.
Upvotes: 1