Floky99
Floky99

Reputation: 732

NextJS mongoose schema "Cannot read properties of undefined"

I have NextJS project with Mongoose schema inside of it. I keep getting following error on dev environment:

TypeError: Cannot read properties of undefined (reading 'Village')

My model file is:

import mongoose from "mongoose";
const {Schema} = mongoose;

const VillageSchema = new mongoose.Schema(
  {
    id: {type: String},
   ...
);

// prettier-ignore
export default mongoose.models.Village || mongoose.model("Village", VillageSchema);

Upvotes: 1

Views: 781

Answers (2)

lukasvo
lukasvo

Reputation: 4852

For anyone who's experiencing issues with Mongoose + NextJS, including OP's error: it seems like you can't use Mongoose in NextJS middleware.

Next.js middleware runs in the Edge Runtime, which doesn't support the full Node.js APIs that Mongoose needs. From the Next.js documentation:

Middleware runs on the Edge Runtime. The Edge Runtime is more limited than the Node.js runtime and supports a subset of Node.js APIs.

A workaround could be to move the logic that needs your database to a separate endpoint and call that endpoint from the middleware.

Upvotes: 0

lpizzinidev
lpizzinidev

Reputation: 13274

Try to add optional chaining to the exported value:

// prettier-ignore
export default mongoose.models?.Village || mongoose.model("Village", VillageSchema);

Upvotes: 2

Related Questions