[英]Router instances in Node.js with express with a database
As far as I can gather from the Express documentation , when you declare an express.Router()
, it creates a single instance of a router that you can then assign a routing path and execute logic with. 据我从Express文档中了解到的,当您声明
express.Router()
,它会创建一个路由器实例,然后您可以为其分配路由路径并执行逻辑。 The documentation says to think of a router like a mini-app for a specific route or routes, which makes sense. 该文档说,可以将路由器想像成用于特定路由的微型应用程序,这很有意义。
I'm trying to strategize what to wrap my database connection around (using mongodb, let's say via mongoose, but it shouldn't matter). 我试图制定策略来包装数据库连接(使用mongodb,例如通过mongoose进行,但这没关系)。 I of course don't want to open a new database connection on every route call, and I assume that if I wrap it around a router only one
Router()
instance will only be created. 我当然不希望在每个路由调用中都打开一个新的数据库连接,并且我假设如果将它包装在路由器上,则只会创建一个
Router()
实例。 In other words, if I went to /routes/index.js
, defined a Router()
and then opened a database connection, then within it did router.get
(or router.post
, etc.), I would be opening one database connection when launching the app, not one per hit on that route. 换句话说,如果我去
/routes/index.js
,定义一个Router()
然后打开一个数据库连接,然后在其中进行router.get
(或router.post
等),那么我将打开一个数据库。启动应用程序时连接,而不是该路线上的每次点击。
Yet there might be other routes beyond index.js
where I want access to the database. 但是除
index.js
之外,还有其他一些我想访问数据库的路由。 So alternatively, could I wrap the database connection around the app.use
route handlers and other middleware within the main app.js
file, then require('../app')
in /routes
files and add the database connection to module.exports
in app.js
, and finally define route logic in other files like /routes/index.js
? 因此,或者,我可以将数据库连接围绕
app.use
在主app.js
文件中使用路由处理程序和其他中间件,然后在/routes
文件中使用require('../app')
并将数据库连接添加到module.exports
在app.js
,最后在/routes/index.js
等其他文件中定义路由逻辑?
I'm a little confused on how to structure everything. 我对如何组织一切感到有些困惑。 Any guidance would be much appreciated.
任何指导将不胜感激。
If you are using mongoose, you can just connect once with some code like this: 如果您使用猫鼬,则只需使用以下代码连接一次即可:
mongoose.connect("mongodb://127.0.0.1:27017/test");
mongoose.connection.on('error', console.error.bind(console, 'Db connection error:'));
// Start the server once we have connected to the database.
mongoose.connection.once('open', () => {
console.log('Db connection open.');
app.listen(3000, function () {
console.log('Listening on port 3000');
});
});
And then, if you have a mongoose model named Foo
set up like 然后,如果您将名为
Foo
的猫鼬模型设置为
const Foo = mongoose.model('Foo', fooSchema); // fooSchema is a mongoose.Schema
Then in your route you can use it like so: 然后在您的路线中可以像这样使用它:
const router = express.Router();
const Foo = require('./models/foo');
router
.route('/foos/:foo_id')
.get((req, res)=> {
Foo.findById(req.params.foo_id, (err, foo) => {
if (err) return res.sendStatus(500);
if (!foo) return res.status(404).send('Foo not found.');
res.status(200).json(foo);
});
});
This kind of setup lets mongoose handle connection pooling. 这种设置使猫鼬可以处理连接池。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.