4

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.used 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?

4

1 回答 1

1

你的代码看起来不错。我认为问题在于您使用的是“req.db.models”而不仅仅是“req.models”。从文档中:

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

并且:

您可以多次调用 orm.express 以获得多个数据库连接。跨连接定义的模型将在req.models中连接在一起。不要忘记在 app.use(app.router) 之前使用它,最好是在你的资产公用文件夹之后。

一切都在“模型”下混合在一起,数据库之间没有区别。这意味着你不能在多个数据库中为你的模型命名相同的东西,但是 c'est la guerre。

于 2014-07-19T02:12:21.903 回答