很抱歉在这里迟到了一点,但也许我的回答会对寻求此类问题答案的其他人有所帮助。
我假设您正在努力解决这些问题:
- 如何在项目之间重用数据库连接
您可以定义一次 MongoClient 对象,然后在项目中的多个模块中重复使用它,如下所示:
dbUtil.js持有MongoClient对象的定义:
const MongoClient = require('mongodb').MongoClient;
const SERVER_URI = // link to your server, for example: 'http://localhost:27017';
const DB_NAME = // database name, for example: 'test';
/* @WHY?:
(option 1?) : to let the server assign objectId instead of Node driver,
(option 2 & 3?) : to get rid of deprecation warnings
*/
const clientObj = new MongoClient(`${SERVER_URI}/${DB_NAME}`, {
forceServerObjectId: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
module.exports = {
client: clientObj,
dbName: DB_NAME
}
在另一个需要使用定义连接的模块中:
const { client, dbName } = require('dbUtil');
// Because client.connect() return a Promise, you should wrap everything
// inside an immediately-invoked expression like this
(async () => {
await client.connect(); // at first you need to open the connection client
const dbO = await client.db(dbName); // get the connection to database
/* perform database operations, for example:
dbO.collection(users).insertOne({ name:'mongoadmin' });
*/
client.close(); // remember to close the connection when you're done
})();
因此,在 Mongo 本地驱动程序中,您必须先激活与客户端的连接,然后使用 client.dbO.collection('users')(它返回一个 Promise),而不是 Mongoose 使用 User.find().exec() 的方式。
- Passport 到底是什么以及为什么您的项目需要它
Passport 是 Express 的身份验证中间件,支持来自 Facebook、Google、JWT... 和许多其他身份验证策略的身份验证。当您需要支持来自多个身份验证门户的身份验证时,它会很有帮助。但是,这不是必须的。
有时从第三方库应用另一层抽象不仅对您和您的项目毫无意义,而且会使您现有的代码库过于复杂。您选择不使用 Mongoose 并改用 MongoDb 本机驱动程序,表示您不需要 schema 和 model 的东西。对于相同的逻辑,我认为没有必要调整 Passport。此链接可能对您有所帮助:another Stackoverflow post
要使用 JSON Web 令牌对您的 Express 路由应用身份验证,您需要执行以下步骤:
- 为登录的用户生成令牌
- 验证令牌
- 定义受保护的路由并为它们编写中间件
所有这些任务都可以在没有任何第三方模块/库的情况下完成!