Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mongoose does not work with latest Next.js version (14.0.4 > 14.0.5-canary.14) #14183

Closed
2 tasks done
edxeth opened this issue Dec 16, 2023 · 26 comments
Closed
2 tasks done
Labels
can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. Stale

Comments

@edxeth
Copy link

edxeth commented Dec 16, 2023

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.0.3

Node.js version

21.4.0

MongoDB server version

7.0.4

Typescript version (if applicable)

5.3.2

Description

Mongoose throws error on connection.
Affected versions: ^14.0.4
Not affected versions 13.5.6, 14.0.1, 14.0.2, 14.0.3

○ Compiling /api/mongodb-test ...
 ✓ Compiled /api/mongodb-test in 2.2s
(node:49) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 ⨯ node_modules/mongoose/lib/mongoose.js (102:30) @ new Mongoose
 ⨯ TypeError: Cannot set properties of undefined (setting 'base')
    at new Mongoose (/home/user/src/.next/server/chunks/node_modules_mongoose_lib_9694d2._.js:13153:32)
    at Object.<anonymous> (/home/user/src/.next/server/chunks/node_modules_mongoose_lib_9694d2._.js:14129:49)
    at [project]/node_modules/mongoose/lib/mongoose.js [app-rsc] (ecmascript) (/home/user/src/.next/server/chunks/node_modules_mongoose_lib_9694d2._.js:14133:3)
    at instantiateModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:490:23)
    at getOrInstantiateModuleFromParent (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:541:12)
    at commonJsRequire (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:127:20)
    at Object.<anonymous> (/home/user/src/.next/server/chunks/node_modules_mongoose_lib_9694d2._.js:16393:18)
    at [project]/node_modules/mongoose/lib/index.js [app-rsc] (ecmascript) (/home/user/src/.next/server/chunks/node_modules_mongoose_lib_9694d2._.js:16397:3)
    at instantiateModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:490:23)
    at getOrInstantiateModuleFromParent (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:541:12)
    at commonJsRequire (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:127:20)
    at Object.<anonymous> (/home/user/src/.next/server/chunks/node_modules_mongoose_d0f576._.js:13:18)
    at [project]/node_modules/mongoose/index.js [app-rsc] (ecmascript) (/home/user/src/.next/server/chunks/node_modules_mongoose_d0f576._.js:66:3)
    at instantiateModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:490:23)
    at getOrInstantiateModuleFromParent (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:541:12)
    at esmImport (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:113:20)
    at /home/user/src/.next/server/chunks/_df3f80._.js:32:137
    at [project]/core/lib/mongodb.ts [app-rsc] (ecmascript) (/home/user/src/.next/server/chunks/_df3f80._.js:68:3)
    at instantiateModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:490:23)
    at getOrInstantiateModuleFromParent (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:541:12)
    at esmImport (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:113:20)
    at /home/user/src/.next/server/chunks/_df3f80._.js:76:126
    at [project]/app/api/mongodb-test/route.ts [app-rsc] (ecmascript) (/home/user/src/.next/server/chunks/_df3f80._.js:102:3)
    at instantiateModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:490:23)
    at getOrInstantiateModuleFromParent (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:541:12)
    at esmImport (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:113:20)
    at /home/user/src/.next/server/chunks/node_modules_next_dist_718420._.js:3891:142
    at [project]/node_modules/next/dist/esm/build/templates/app-route.js/(INNER_APP_ROUTE)/[project]/app/api/mongodb-test/route.ts [app-rsc] (ecmascript) (ecmascript) (/home/user/src/.next/server/chunks/node_modules_next_dist_718420._.js:3926:3)
    at instantiateModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:490:23)
    at instantiateRuntimeModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:549:12)
    at Object.getOrInstantiateRuntimeModule (/home/user/src/.next/server/chunks/[turbopack]_runtime.js:564:12)
    at Object.<anonymous> (/home/user/src/.next/server/app/api/mongodb-test/route.js:17:26)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at mod.require (/home/user/src/node_modules/next/dist/server/require-hook.js:65:28)
    at require (node:internal/modules/helpers:176:18)
    at requirePage (/home/user/src/node_modules/next/dist/server/require.js:109:84)
    at /home/user/src/node_modules/next/dist/server/load-components.js:59:84
    at async loadComponentsImpl (/home/user/src/node_modules/next/dist/server/load-components.js:59:26)
    at async DevServer.findPageComponentsImpl (/home/user/src/node_modules/next/dist/server/next-server.js:671:36) {
  page: '/api/mongodb-test'
}
null
 ○ Compiling /_error ...
 ✓ Compiled /_error in 1001ms

Steps to Reproduce

Install Next.js (latest & affected: 14.0.4) with TypeScript and App Router
https://nextjs.org/docs/getting-started/installation

.env

# Replace with your MongoDB connection string
MONGODB_URI="mongodb://username:password@localhost:27017/mydatabase"

mongodb.d.ts

import { Mongoose } from "mongoose";

/* eslint-disable no-var */

declare global {
  var mongoose: {
    conn: Mongoose | null;
    promise: Promise<Mongoose> | null;
  };
}

lib/mongodb.ts

import mongoose from "mongoose";

const MONGODB_URI = process.env.MONGODB_URI ;

if (!MONGODB_URI) throw new Error("MONGODB_URI not defined");

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

async function dbConnect() {
  if (cached.conn) {
    return cached.conn;
  }
  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    };
    cached.promise = mongoose
      .connect(MONGODB_URI, opts)
      .then((mongoose) => {
        return mongoose;
      });
  }
  try {
    cached.conn = await cached.promise;
  } catch (e) {
    cached.promise = null;
    throw e;
  }

  return cached.conn;
}

export default dbConnect;

app/api/mongodb-test/route.ts

import { NextResponse } from "next/server";
import dbConnect from "@/lib/mongodb";

export async function GET() {
  try {
    await dbConnect();
    return NextResponse.json({ message: "Connected!" });
  } catch (e) {
    return NextResponse.json(e, { status: 500 });
  }
}

Send an HTTP GET request to: http://localhost:3000/api/mongodb-test

Expected Behavior

No response

@twan-keizer
Copy link

Hello @edxeth,

I had the same error and found your issue when trying to resolve mine. I went back en forth between my commits to see what change caused this issue. It was after a change to my package.json and package-lock.json that this bug first occured.

I removed the package-lock.json and then ran npm install again to create a new package-lock.json and the bug does not occur anymore. Unfortunately I could not find what causes the issue since we use many packages in our project.

We are using Next version 14.0.4-canary.32 (bug I guess that 14.0.4 should also work).

Hopefully this will fix your issue as well!

@edxeth
Copy link
Author

edxeth commented Dec 16, 2023

Hello @edxeth,

I had the same error and found your issue when trying to resolve mine. I went back en forth between my commits to see what change caused this issue. It was after a change to my package.json and package-lock.json that this bug first occured.

I removed the package-lock.json and then ran npm install again to create a new package-lock.json and the bug does not occur anymore. Unfortunately I could not find what causes the issue since we use many packages in our project.

We are using Next version 14.0.4-canary.32 (bug I guess that 14.0.4 should also work).

Hopefully this will fix your issue as well!

Hey there!
I appreciate your help, but I've already given that a shot, and it didn't help. I've tried using npm, yarn, and bun, but none of them seem to work. I can't even downgrade to 14.0.3 or an earlier version because of another bug that's causing issues with turbopack. It's a bit of a mess, to be honest.

@edxeth
Copy link
Author

edxeth commented Dec 16, 2023

@twan-keizer I thought it's worth a try so I've decided to install Next.js 14.0.4-canary.32 and guess what? It's working!
This is definitely a well accepted temporary solution to my other issue that forces me to use 14.0.3 without turbopack...

Edit: the latest working version with Mongoose is 14.0.4-canary.37, for your information.

@vkarpov15 vkarpov15 added this to the 8.0.4 milestone Dec 18, 2023
@vkarpov15 vkarpov15 added the needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue label Dec 18, 2023
@IslandRhythms IslandRhythms added can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. and removed needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue labels Dec 19, 2023
@IslandRhythms
Copy link
Collaborator

From your steps described the route was mongo-test, not mongodb-test. The return NextResponse.json({ "Connected "}) would throw an error since you're passing a keyless object with a value. You have a similar issue with the return in the catch statement. See if patching those fixes your issue.

image

@edxeth
Copy link
Author

edxeth commented Dec 20, 2023

Hi @IslandRhythms
I apologize for the confusion earlier. I made a mistake in my original post. I have now updated my original post with the correct code, which is return NextResponse.json({ message: "Connected "}) and return NextResponse.json(e, { status: 500 }); in the catch statement.
I can't find where the route mongo-test was mentioned (I see mongodb-test), and unfortunately, using the updated JSON code didn't help me resolve the issue. Could you let me know what version of Next.js you're using?

@IslandRhythms
Copy link
Collaborator

Where you describe the route to ping

@IslandRhythms
Copy link
Collaborator

image

@edxeth
Copy link
Author

edxeth commented Dec 21, 2023

Where you describe the route to ping

The route is correctly described as /api/mongodb-test, besides, I've got the same exact dependencies as you in my package.json

What am I missing here? I'm confused. I'm able to GET request the route, no problem whatsoever. Switching Next.js versions, with the same exact Mongoose implementation as shown here, causes Mongoose to throw the error I shared in my original post.

@vkarpov15
Copy link
Collaborator

@edxeth can you please create a GitHub repo that demonstrates the issue you're seeing? We're testing with https://github.com/IslandRhythms/demo-next-error and everything seems to work fine.

@edxeth
Copy link
Author

edxeth commented Dec 21, 2023

@vkarpov15 I've just given the same exact Mongoose implementation a try in a fresh Next.js project (versions 14.0.4 and 14.0.5-canary.23), and it's working smoothly (why I didn't try this earlier?). However, in the codebase I'm currently working on, it only functions without any issues when I use Next.js versions 14.0.4-canary.32 and 14.0.4-canary.37. Anything else seems to trigger the error I mentioned in my original post. Unfortunately, I can't share the repository since it contains proprietary code. So, I'll dig into it further to identify the problem myself. Perhaps it's related to a specific package or configuration.

Thanks once again for your assistance, and in the meantime, I'll stick to using Next.js 14.0.4-canary.37

@vkarpov15 vkarpov15 removed this from the 8.0.4 milestone Dec 26, 2023
@vkarpov15
Copy link
Collaborator

@edxeth let us know if you find anything more. Are you at least able to share the project's dependencies so we can look and see if anything looks suspicious? If this issue doesn't happen on a clean project, it may be because some other dependency is causing trouble.

@edxeth
Copy link
Author

edxeth commented Dec 27, 2023

@vkarpov15 my package.json:

{
  "name": "protocol",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbo",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "migrate:init": "migrate-mongo init -m esm",
    "migrate:status": "migrate-mongo status -f './mongodb.config.mjs'",
    "migrate:create": "migrate-mongo create -f './mongodb.config.mjs'",
    "migrate:up": "migrate-mongo up -f './mongodb.config.mjs'",
    "migrate:down": "migrate-mongo down -f './mongodb.config.mjs'"
  },
  "dependencies": {
    "@fortawesome/fontawesome-free": "6.5.1",
    "@fortawesome/fontawesome-svg-core": "6.5.1",
    "@fortawesome/free-brands-svg-icons": "6.5.1",
    "@fortawesome/free-solid-svg-icons": "6.5.1",
    "@fortawesome/react-fontawesome": "0.2.0",
    "@headlessui/react": "1.7.17",
    "@heroicons/react": "2.0.18",
    "@rainbow-me/rainbowkit": "1.3.2",
    "@rainbow-me/rainbowkit-siwe-next-auth": "0.3.4",
    "@reduxjs/toolkit": "2.0.1",
    "@tailwindcss/forms": "0.5.7",
    "autoprefixer": "10.4.16",
    "daisyui": "4.4.24",
    "ethers": "6.9.1",
    "migrate-mongo": "11.0.0",
    "mongodb": "6.3.0",
    "mongoose": "8.0.3",
    "next": "14.0.4-canary.37",
    "next-auth": "4.24.5",
    "postcss": "8.4.32",
    "prettier": "3.1.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-redux": "9.0.4",
    "redux": "5.0.1",
    "siwe": "2.1.4",
    "tailwindcss": "3.4.0",
    "viem": "1.21.1",
    "wagmi": "1.4.12"
  },
  "devDependencies": {
    "@types/node": "20.10.5",
    "@types/react": "18.2.45",
    "@types/react-dom": "18.2.18",
    "@typescript-eslint/eslint-plugin": "6.16.0",
    "eslint": "8.56.0",
    "eslint-config-next": "14.0.4",
    "ts-node": "10.9.2",
    "typescript": "5.3.3"
  },
  "resolutions": {
    "whatwg-url": "13.0.0"
  }
}

Do you mind trying with yarn and bun package managers?

@dshaby
Copy link

dshaby commented Jan 2, 2024

Hey thanks for opening this thread, it was quite helpful. I was experiencing the same issue and error message with "mongoose": "^8.0.3", and "next": "14.0.4",

After updating to "next": "14.0.4-canary.37",, I was able to successfully connect to mongodb/mongoose, however, I still get this weird error message, which I saw @edxeth also mentioned initially:

(node:77137) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

@edxeth
Copy link
Author

edxeth commented Jan 2, 2024

Hey there @dshaby
I'm glad to hear that the thread was beneficial for both of us. Would you be willing to share your package.json with the community? I'm interested in finding out which dependencies we have in common.

@vkarpov15 vkarpov15 added needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue and removed can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. labels Jan 3, 2024
@vkarpov15 vkarpov15 modified the milestones: 8.0.4, 8.0.5 Jan 3, 2024
@WinnieS0728
Copy link

hello I think I have similar issue here. I also got TypeError: Cannot set properties of undefined in my code.

but in my case I got TypeError: Cannot set properties of undefined (setting '$wasForceClosed') when I use mongoose.createConnection and close().

  • package.json
"dependencies": {
    "mongoose": "^8.0.3",
    "react": "^18",
    "react-dom": "^18",
    ... and other package I think not cause this error.
},
"devDependencies": {
    "next": "^14.0.4",
    "typescript": "^5"
    ... and other package I think not cause this error.
}
  • folder tree (using nextJS app router)
app/api
└── mongoDB
    └── basicSetting
        └── [type]
            ├── methods.ts
            └── route.ts
  • route.ts
export async function GET(_: NextRequest, { params: { type } }: params) {
    let disconnect;
    try {
        const conn = mongoose.createConnection(`${process.env.MONGO_URL}/basic-setting`)
        // three schema start with DB_ is import from schema file
        const member = conn.model('members', DB_basicSetting_member)
        const category = conn.model('categories', DB_basicSetting_category)
        const tag = conn.model('tags', DB_basicSetting_tag)
        disconnect = conn.close
        switch (type) {
            case 'member':
                const member_res = await member.find().sort({ threshold: 1 }).lean()
                return NextResponse.json(member_res, { status: 200 })
            case "category":
                const categories_res = await category.find().lean()
                return NextResponse.json(categories_res, { status: 200 })
            case 'tag':
                const tag_res = await tag.find().lean()
                return NextResponse.json(tag_res, { status: 200 })
            default:
                return NextResponse.json('type error', { status: 404 })
        }
    } catch (error) {
        console.log(error);
        return NextResponse.json(error, { status: 500 })
    } finally {
        if (disconnect) {
            await disconnect()
        }
    }
}
  • page.tsx
export default function SettingPage() {
  return (
    <section className="px-8">
      <h2 className="text-center text-xl uppercase">基本設定</h2>
      <div className="grid gap-2">
        <MemberSetting />    // this one call fetch("/api/mongoDB/basicSetting/member");
        <CategorySetting />    // this one call fetch("/api/mongoDB/basicSetting/category");
        <TagsSetting />     // this one call fetch("/api/mongoDB/basicSetting/tag");
      </div>
    </section>
  );
}

and I got this when I run dev and load my page

TypeError: Cannot set properties of undefined (setting '$wasForceClosed')
    at close (/Users/winnie.chang/Documents/GitHub/shop-cart/node_modules/mongoose/lib/connection.js:855:26)
    at GET (webpack-internal:///(rsc)/./app/api/mongoDB/basicSetting/[type]/route.ts:59:19)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/winnie.chang/Documents/GitHub/shop-cart/node_modules/next/dist/compiled/next-server/app-route.runtime.dev.js:6:63251

I'm new in mongoose about two weeks. so maybe is some typing error in my code.
if I not close connection, it will work and return the right response. but every time I load to this page create new connection. and few time later I reach the mongoDB max connection and broke everything till I restart a new run dev.
after some console.log testing I think maybe it call close before createConnection connect success. but how to solve this problem.
but I try to find solution and got noting 🥲.

@WinnieS0728
Copy link

well I solve my problem but I don't know why

I create a function call connectDB

function connectDB(dbName: "basic-setting") {
    const conn = createConnection(`${process.env.MONGO_URL}`, {
        dbName
    })
    conn.once('connected', () => console.log(`connect ${dbName} success`))
    conn.once('close', () => console.log(`close ${dbName}`))

    conn.model("members", DB_basicSetting_member_schema)
    conn.model("categories", DB_basicSetting_category_schema)
    conn.model("tags", DB_basicSetting_tag_schema)

    return conn
}

and async function GET1 for testing

export async function GET1(req: NextRequest, { params: { type } }: params) {
    const conn = connectDB('basic-setting')
    const DB_basicSetting_member = conn.models.members
    const DB_basicSetting_category = conn.models.categories
    const DB_basicSetting_tag = conn.models.tags

    try {
        switch (type) {
            case 'member':
                const member_res = await DB_basicSetting_member.find().sort({ threshold: 1 }).lean()
                return NextResponse.json(member_res, { status: 200 })
            case "category":
                const categories_res = await DB_basicSetting_category.find().lean()
                return NextResponse.json(categories_res, { status: 200 })
            case 'tag':
                const tag_res = await DB_basicSetting_tag.find().lean()
                return NextResponse.json(tag_res, { status: 200 })
            default:
                return NextResponse.json('type error', { status: 404 })
        }
    } catch (error) {
        console.log(error);
        return NextResponse.json(error, { status: 500 })
    } finally {
        await conn.close()
    }
}

and async function GET2 for testing

export async function GET2(req: NextRequest, { params: { type } }: params) {
    // first try
    const conn = connectDB('basic-setting')
    const DB_basicSetting_member = conn.models.members
    const DB_basicSetting_category = conn.models.categories
    const DB_basicSetting_tag = conn.models.tags
    const disconnect = conn.close

    // second try    
     const { models: {
        members: DB_basicSetting_member,
        categories: DB_basicSetting_category,
        tags: DB_basicSetting_tag
    }, close: disconnect } = connectDB('basic-setting')

    // both try not working

    try {
        switch (type) {
            case 'member':
                const member_res = await DB_basicSetting_member.find().sort({ threshold: 1 }).lean()
                return NextResponse.json(member_res, { status: 200 })
            case "category":
                const categories_res = await DB_basicSetting_category.find().lean()
                return NextResponse.json(categories_res, { status: 200 })
            case 'tag':
                const tag_res = await DB_basicSetting_tag.find().lean()
                return NextResponse.json(tag_res, { status: 200 })
            default:
                return NextResponse.json('type error', { status: 404 })
        }
    } catch (error) {
        console.log(error);
        return NextResponse.json(error, { status: 500 })
    } finally {
        await disconnect()
    }
}

GET1 work success, but not GET2

the only different is I const conn.close as disconnect and call disconnect instead of call original conn.close.

then I try this on GET2 second try

    const { models: {
        members: DB_basicSetting_member,
        categories: DB_basicSetting_category,
        tags: DB_basicSetting_tag
    }, ...other } = connectDB('basic-setting')
    console.log(other.close); // error show here

and I got some type error

Property 'close' does not exist on type '{ collections: { [index: string]: Collection<Document>; }; config: any; db: Db; host: string; id: number; name: string; pass: string; port: number; plugins: any[]; readyState: ConnectionStates; ... 15 more ...; eventNames(): (string | symbol)[]; }'.

I have no idea why this happen

@vkarpov15
Copy link
Collaborator

@WinnieS0728 your issue is unrelated: purely due to incorrect JavaScript. const disconnect = conn.close leads to losing context when calling disconnect(), more info here on how this works in JavaScript`.

@WinnieS0728
Copy link

ok thank you

@dshaby
Copy link

dshaby commented Jan 16, 2024

Sure @edxeth. I've pasted my dependencies below.

{
	"dependencies": {
		"@react-google-maps/api": "^2.19.2",
		"mongoose": "^8.0.4",
		"next": "14.0.4-canary.37",
		"react": "^18",
		"react-dom": "^18",
		"react-icons": "^5.0.1",
		"styled-components": "^6.1.8",
		"use-places-autocomplete": "^4.0.1"
	},
	"devDependencies": {
		"@types/node": "^20",
		"@types/react": "^18",
		"@types/react-dom": "^18",
		"autoprefixer": "^10.4.16",
		"eslint": "^8.56.0",
		"eslint-config-next": "^14.0.4",
		"husky": "^8.0.3",
		"lint-staged": "^15.2.0",
		"postcss": "^8.4.33",
		"postcss-styled-syntax": "^0.6.0",
		"prettier": "^3.2.1",
		"stylelint": "^16.1.0",
		"stylelint-config-standard": "^36.0.0",
		"tailwindcss": "^3.4.1",
		"typescript": "^5"
	},
	"lint-staged": {
		"*.{js,ts,tsx}": [
			"prettier --write"
		]
	}
}

Hope this helps!

@twan-keizer
Copy link

@edxeth I'm still using 14.0.4-canary.37 to make npm run dev --turbo work, did you find another solution for this? I spend some more time upgrading other dependencies without result.

I could resolve the punycode deprecation warning by using node v20.0.10, so this had nothing to do with the issue.

@dshaby
Copy link

dshaby commented Jan 16, 2024

@twan-keizer Thanks for that. Did you mean 20.10.0 (not 20.0.10?

@twan-keizer
Copy link

@dshaby yes it's a typo, version 20.10.0

@vkarpov15 vkarpov15 modified the milestones: 8.1.1, 8.1.2 Jan 23, 2024
@vkarpov15 vkarpov15 modified the milestones: 8.1.2, 8.1.3 Feb 8, 2024
@vkarpov15 vkarpov15 modified the milestones: 8.1.3, 8.1.4 Feb 15, 2024
@vkarpov15 vkarpov15 modified the milestones: 8.2.1, 8.2.2 Mar 4, 2024
@jmikrut
Copy link

jmikrut commented Mar 5, 2024

Seeing the same issue as OP. We're on an older version of Mongoose (6.12.3) and this only happens with Turbopack. Using Next.js with Webpack works fine.

More info: if I console.log this.schema in the Mongoose constructor before this.Schema.prototype.base = this is executed and the error happens, I see differences when I run Turbopack vs. Webpack.

With Webpack:

[Function: Schema] {
  reserved: [Object: null prototype] {
    validate: 1,
    toObject: 1,
    save: 1,
    remove: 1,
    populated: 1,
    isNew: 1,
    isModified: 1,
    init: 1,
    get: 1,
    errors: 1,
    collection: 1,
    removeListener: 1,
    listeners: 1,
    emit: 1,
    prototype: 1
  },
  Types: {
    String: [Function: SchemaString] {
      schemaName: 'String',
      defaultOptions: {},
      _cast: [Function: castString],
      cast: [Function: cast],
      _defaultCaster: [Function (anonymous)],
      get: [Function (anonymous)],
      set: [Function: set],
      _checkRequired: [Function (anonymous)],
      checkRequired: [Function (anonymous)]
    },
    // the rest of the types here (omitted for simplicity)
  }
}

And with Turbopack:

{
  String: [Function: SchemaString] {
    schemaName: 'String',
    defaultOptions: {},
    _cast: [Function: castString],
    cast: [Function: cast],
    _defaultCaster: [Function (anonymous)],
    get: [Function (anonymous)],
    set: [Function: set],
    _checkRequired: [Function (anonymous)],
    checkRequired: [Function (anonymous)]
  },
  // the rest of the types here (omitted for simplicity)
}

@vkarpov15
Copy link
Collaborator

@jmikrut that output is strange, makes it look like with Turbopack you're getting just Mongoose's lib/schema/index.js file, rather than lib/schema.js.

I tried to come up with a repro based on your instructions, but I'm unable to repro. Here's the GitHub repo I put together. Mongoose v6.12.3 and 1 API endpoint that just loads a document from Mongoose. Can you please take a look and see if you can modify this repo to trigger the issue you're seeing?

Based on the output you pasted I suspected it might be an OSX vs Linux issue due to case insensitive filenames in OSX, but that doesn't seem to be the case, I'm able to hit http://localhost:3000/api/hello on both OSX and Linux.

@vkarpov15 vkarpov15 added can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. and removed needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue labels Mar 7, 2024
@vkarpov15 vkarpov15 removed this from the 8.2.2 milestone Mar 7, 2024
Copy link

This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days

@github-actions github-actions bot added the Stale label Mar 22, 2024
Copy link

This issue was closed because it has been inactive for 19 days and has been marked as stale.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Mar 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
can't reproduce Mongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity. Stale
Projects
None yet
Development

No branches or pull requests

7 participants