Can not connet to mongodb database in nextjs

environment

  • nodejs: v18.17.0
  • nextjs: v13.4.13
  • mongodb version: mongodb communtity
  • mongodb-tool: mongodbcompass

details:


my guess:

  • nextjs works
  • mongodb can not connect, but I can not figure out why it not working as my expect. I might write the wrong code.

src/pages/api/v1/knowledge below:

import { MongoClient, Db } from "mongodb";
import { NextApiRequest, NextApiResponse } from "next";

const resolveGetRequest = async (
  req: NextApiRequest,
  res: NextApiResponse,
  db: Db
) => {
  const collection = db.collection("KnowledgePointComments");
  const data = await collection.find({}).toArray();
  res.status(200).json({
    code: "0",
    messgae: "success",
    data: "hello-world!",
  });
};

const resolvePostRequest = async (
  req: NextApiRequest,
  res: NextApiResponse,
  db: Db
) => {};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const url = "mongodb://localhost:27017";
  const dbName = "TEST_FRONTEND_EVERYDAY";
  const client = new MongoClient(url);
  // console.log(client);
  try {
    const __res = await client.connect();
    console.log("@", __res);
    console.log("connect mongodb success!");

    const db: Db = client.db(dbName);

    // 获取随机知识点
    if (req.method === "GET") {
      resolveGetRequest(req, res, db);
    }

    // 发布知识点
    if (req.method === "POST") {
      resolvePostRequest(req, res, db);
    }
  } catch (err) {
    res.status(500).json({
      code: "-1",
      message: "unable to connect mongodb",
    });
  } finally {
    await client.close();
  }
}

ps:I had tried these solution.

  • change bandId from 127.0.0.1 to 0.0.0.0 in mongod.cfg
  • restart mongodb

pss:

  • os: windows 10
  • mongodb version: MongoDB 6.0.8 Community
  • host: localhost:27017
  • Cluster: Standalone