繁体   English   中英

如何在 MongoClient.connect 中的 app.use 中插入参数

[英]How to insert parameters in app.use inside MongoClient.connect

我认为在 MongoClient.connect 内部调用 app.use 会更合乎逻辑,以免在路由器内部不断调用 mongoclient。 如何使db.collection.findapp.use中可用?

 const database = dbm.db('db')` inside `app.use('/api/', authRoute)`

    MongoClient.connect(dburl, function(err, dbm) {
    if(err) throw err;
    const database = dbm.db('db') <<<<< this i want use inside app.use
    app.use('/api/', authRoute);

    // Start the application after the database connection is ready
    app.listen(2222);
    console.log("Listening on port 2222");
});

在 authRoute 我添加了const router = require('express').Router({ mergeParams: true }); ,但没关系。 这是可能的? 或者我可以在MongoClient.connect多次调用app.use吗?

提前致谢

TL; DR您不必修改代码,它可以工作。

ZCCADCDEDB567ABAE643E15DCF0974E503Z 可以很容易地做到这一点。 甚至不需要考虑这个问题,因为 Mongoose 会自动完成。 这意味着一旦您在主服务器文件中添加了MongoClient.connect()并通过运行该文件启动应用程序,所有后续文件(在您的情况下为路由器)将自动使用此连接。

例如,这是我用于服务器的代码(在 TypeScript 中)。

import { connect, connection } from 'mongoose';
import { app } from './app';

connect('mongodb://localhost/BaBBS', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex: true,
});

const db = connection;

db.once('open', () => {
    console.log('Successful connection to MongoDB');
});

app.listen(1025, () => {
    console.log('Server up and running on port 80');
});

当我运行代码时,与 Mongoose 逻辑相关的所有内容(例如find )都可以正常工作。

希望这个答案有帮助!

您可以将authRoute定义为工厂 function ,您可以将database连接 object 传递到:

const express = require('express');
const router = express.Router();

module.exports = (db) => {  
    router.post('/login', (req,res) => {
       // you can now use db here
       db.doSomething();
       res.send(...);
    });
    // more routes here
    return router;
}

然后,您可以像这样使用您的工厂 function:

// ...
const database = dbm.db('db')
app.use('/api/', authRoute(database));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM