把中间件放在里面.然后块mongoose.connect可以吗?(更多在问题的主体中)

yrdbyhpb  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(105)

我这里有一个简单的express应用程序,为了使mongoose.connection.getClient()工作,我需要有一个已经建立的数据库连接。把app.use(session()),app.use(passport.initialize()); app.use(passport.session());里面,然后是 Mongoose ,连接?
所以基本上我是在问这个代码结构是否正确

import express from "express";
import mongoose from "mongoose";
import passport from "passport";
import dotenv from "dotenv";
import session from "express-session";
import MongoStore from "connect-mongo";
import routes from "./routes/index.js";
import "./config/passport.js";

//Configurations
const app = express();
dotenv.config();

//Middleware
app.use(express.json());

//Database setup
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true })
   .then(() => {
      console.log("Database connection has been established");

      //Auth middleware
      app.use(session({
         secret: "secret",
         resave: false,
         saveUninitialized: false,
         store: MongoStore.create({ client: mongoose.connection.getClient(), collectionName: "sessions" }),
         cookie: {
            maxAge: 1000 * 60
         }
      }))
      app.use(passport.initialize());
      app.use(passport.session());

      //Server listening
      const PORT = process.env.PORT || 6001;
      app.listen(PORT, () => { console.log(`App is listeting on PORT ${PORT}`); });

   })
   .catch((err) => { console.log(`Database connection error: ${err}`); })

//Router
app.use(routes);

//Error handler
app.use((err, req, res, next) => {
   res.json({error: "Error:("})
})
ybzsozfc

ybzsozfc1#

将错误处理中心移到.then()块之外时,确保它捕获数据库连接过程中发生的错误以及应用程序执行过程中可能发生的其他错误

相关问题