TypeError:mongoose__WEBPACK_IMPORTED_MODULE_0___default(...).connect 不是一个函数

问题描述 投票:0回答:1

我正在尝试连接到我的 MongoDB 数据库。我已按如下方式导入猫鼬:

import mongoose from "mongoose";

当我尝试使用

mongoose.connect(...)
连接到我的 MongoDB 数据库时,它返回一个错误:

[TypeError: mongoose__WEBPACK_IMPORTED_MODULE_0___default(...).connect 不是一个函数]

我正在 Next.js 中编写代码。数据库连接函数在中间件脚本(而不是前端)中调用。这是我的脚本:

import mongoose from "mongoose";

const connect = async() => {
    try {
        mongoose.connect("mongodb+srv://root:[email protected]/?retryWrites=true&w=majority")
            .then(() => {
                console.log("Database connected!");
            })
    } catch(err) {
        console.error("Something went wrong connecting to database");
        console.error(err);
    }
}

中间件:

export const middleware = async (request: NextRequest) => {
    await database.connect();
}

export const config = {}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

我对此非常困惑,无法在网上找到真正的答案。我已经尝试了很多,主要是建议猫鼬的导入应该不同,我已经尝试过了。我尝试过这些:

import mongoose from "mongoose";
import * as mongoose from "mongoose";
import mongoose = require("mongoose");
import { connect } from 'mongoose';

谁有解决办法吗?

node.js mongoose next.js
1个回答
0
投票

我正在使用 next.js 14,并且在使用服务器操作并尝试连接到我的数据库时遇到相同的错误。

我只需要使用

"use server"
在文件顶部我调用
connectToDatabase
函数的地方。

© www.soinside.com 2019 - 2024. All rights reserved.