You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13(TypeScript)项目连接MongoDB Atlas失败问题求助

Next.js 13(TypeScript)项目连接MongoDB Atlas失败问题求助

大家好,我最近在开发Next.js 13(TypeScript)项目时,尝试连接MongoDB Atlas遇到了棘手的问题,折腾了一天多试了各种方法还是没解决,希望能得到大家的帮助。

问题描述

每次发起GET/POST请求到API路由时,控制台先显示“connected”,但后续请求会进入catch块执行错误逻辑。从报错信息来看,核心问题是无法连接到Atlas集群,提示IP未在白名单中,但我已经尝试过添加IP,还是没解决。

错误日志

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/
at _handleConnectionErrors (D:\Metaverse\Next JS\fullstack-blog\node_modules\mongoose\lib\connection.js:788:11)
at NativeConnection.openUri (D:\Metaverse\Next JS\fullstack-blog\node_modules\mongoose\lib\connection.js:763:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async dbConnect (webpack-internal:///(rsc)/./utils/db.ts:32:19)
at async GET (webpack-internal:///(rsc)/./app/api/posts/route.ts:15:9)
at async eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:253:37) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-lh1wnuj-shard-00-01.ihrszuz.mongodb.net:27017' => [ServerDescription],
'ac-lh1wnuj-shard-00-02.ihrszuz.mongodb.net:27017' => [ServerDescription],
'ac-lh1wnuj-shard-00-00.ihrszuz.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-3uuvzc-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
- error Error: ERROR
at POST (webpack-internal:///(rsc)/./app/api/posts/route.ts:50:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:253:37)

我的代码片段

数据库连接代码(utils/db.ts)

import mongoose from "mongoose";

const connectMongo = () => {
  try {
    const mongoURI = process.env.MONGO;
    if (!mongoURI) {
      console.log("mongoURI");
      throw new Error(
        "MongoDB URI not found. Please set the 'MONGO' environment variable."
      );
    }
    mongoose.connect(mongoURI);
    console.log("connected");
  } catch (error) {
    console.log("error");
  }
};

export default connectMongo;

API路由代码(app/api/posts/route.ts)

import Post from "@/models/Post";
import dbConnect from "@/utils/db";
import { NextRequest, NextResponse } from "next/server";

export const GET = async (request: NextRequest) => {
  try {
    console.log("CONNECTED MONGO");
    await dbConnect();
    console.log("CONNECTED MONGO");
    const posts: any = await Post.find();
    console.log("POSTS Fecthed");
    return NextResponse.json({
      success: posts,
    });
  } catch (error) {
    console.log(error);
    return new NextResponse("DATABASE ERROR", { status: 500 });
  }
};

export const POST = async (request: NextRequest) => {
  const { title, desc, image, username, content } = await request.json();
  try {
    console.log("CONNECTING TO MONGO");
    await dbConnect();
    console.log("CONNECTED TO MONGO");
    console.log("CREATING DOCUMENT");
    const post = await new Post({
      title,
      desc,
      image,
      username,
      content,
    }).save();
    console.log("CREATED DOCUMENT");
    return NextResponse.json({
      success: post,
    });
  } catch (error) {
    console.log("error");
    console.log(error);
    throw new Error("ERROR");
  }
};

我已经尝试过的操作

  • 在MongoDB Atlas控制台添加了当前机器的公网IP到白名单
  • 确认环境变量MONGO的连接字符串正确(替换了用户名、密码等占位符)
  • 重启过开发服务器和MongoDB Atlas集群

希望大家能帮我找到问题所在,谢谢!

备注:内容来源于stack exchange,提问作者Ahsan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 08:53:05