Next JS - MongoDB / 504 GATEWAY_TIMEOUT Vercel at Dynamic Route

0aydgbwb  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(122)

我使用的是Mongo DB shared clustered和Vercel free。首先,本地没有超时问题,我的MongoDB连接使用mongoose,所以我总是调用相同的连接。此外,在vercel上,问题是我第一次连接,之后页面缓存路由,最多2秒内加载没有问题。我路由中的动态页面是由SSG生成的,在本例中,它用于课程和类,路由看起来像这样https://www.mateomolfino.com/src/courses/1/1

蒙哥比. js

if (!process.env.MONGODB_URI) {
   throw new Error('Invalid/Missing environment variable: 
 "MONGODB_URI"')
 }

 const uri = process.env.MONGODB_URI
 const options = {}

 let client
 let clientPromise

 if (process.env.NODE_ENV === 'development') {
 if (!global._mongoClientPromise) {
 client = new MongoClient(uri, options)
 global._mongoClientPromise = client.connect()
 }
 clientPromise = global._mongoClientPromise
 } else {
   client = new MongoClient(uri, options)
  clientPromise = client.connect()
 }

# SSR
# 
export async function getServerSideProps(context: any) {

  await db()
  const { params, query, req, res } = context
  const session = await getSession({ req })
  const cookies = parseCookies(context)
  const userCookie = cookies?.user ? JSON.parse(cookies.user) : 
  session?.user
  const email = userCookie?.email   
  const { classId, id } = params
  const clase = await getClassById(classId, id)
  const user = await updateActualCourseSS(email, id, classId)

  return {
    props: { clase, user  }
  }
 }

getClassById

import connectDB from "../../../config/connectDB" 
 import Course from "../../../models/courseModel"
 import User from "../../../models/userModel"
 import Class from "../../../models/classModel"
 import bcrypt from "bcryptjs"

 export async function getClassById(id, courseId) {
   try {
     const res = await Class.where('id').equals(id).populate({ 
     path: 'course', match: {id:      courseId}}).exec()
     const courseToSend = res.filter(r => r.course != null)

     const clase = JSON.parse(JSON.stringify(courseToSend[0]))
     return clase
     } catch (err) {
      console.log(err)
     }
  }

updateActualCourseSS

export async function updateActualCourseSS(email: string, 
   courseId: string, actualChapter: number) {
   try {
    console.log('connected')
    const user: any | null = await User.findOne({ email: email 
    }).exec()
    const courseDB: CoursesDB | null = await Course.findOne({ id: 
    courseId}).exec()

    const index = user?.courses.findIndex((course: CourseUser) => 
    course.course.valueOf() === courseDB?._id.valueOf())

    index != null && user != null ? 
    user.courses[index].actualChapter = actualChapter : null

    user.courses[index].actualTime = 0;

    await user?.save()

    return JSON.parse(JSON.stringify(user));

     } catch (err) {
      console.log(err)
     }
    }
zzlelutf

zzlelutf1#

您必须转到“vercel-〉integrations”:[https://vercel.com/dashboard/integrations][1]
[1]:https://vercel.com/dashboard/integrations并将Vercel与MongoDB Atlas连接。

相关问题