#Mongoose + Middleware: Cannot read properties of undefined

2 messages · Page 1 of 1 (latest)

tribal parrot
#

Using Next.js 14 app router with mongoose, I encounter this error as soon as I import a server action into my middleware:

 ⨯ src\models\nachricht.ts (38:0) @ <unknown>
 ⨯ Cannot read properties of undefined (reading 'Message')
 36 | );
 37 |
> 38 | export default mongoose.models.Message || mongoose.model('Message', messageSchema)

The root of the issue seems to be that [middleware in Next.js is an edge runtime and DB connections aren't recommended in there](#1142075909856305162 message).

Why isn't it possible to connect to a DB in Next.js middleware? And what's the alternative?

(Temporary) solution

I've solved the problem temporarily by moving saveMessage() to a seperate file for server actions which establish database connection and use models.
But this is indeed only a temporary fix, because sooner or later the getUniqueCityNamesAndSlugs() action will also work with a database connection (instead of a JSON file).

Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

hollow cobaltBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)