Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose.connect not a function type error

I am running a database connection to mongoDB using mongoose(v 8.6.2) in next.js and it keeps throwing an error of .connect not being a function, this is my database.js file

import mongoose from 'mongoose';


let isConnected = false; // track the connection

export const connectToDB = async () => {
  

  if(isConnected) {
    console.log('MongoDB is already connected');
    return;
  }

  try {
    await mongoose.connect(process.env.MONGODB_URI, {
      dbName: "share_prompt",
      useNewUrlParser: true,
      useUnifiedTopology: true,
      strictQuery: true
    })

    isConnected = true;

    console.log('MongoDB connected')
  } catch (error) {
    console.log(error);
  }
}

I've tried checking mongoose documentation to see if there's any new syntax for .connect, but I've gotten nothing

like image 746
Watti Favour Avatar asked Jul 30 '26 19:07

Watti Favour


1 Answers

I am running a database connection to mongoDB using mongoose(v 8.6.2) in next.js and it keeps throwing an error of .connect not being a function,

It is happening because to call a Server Action in a Client Component, create a new file and add use server directive at the top of it. All exported functions within the file will be marked as Server Actions that can be reused in both Client and Server Components.

Just do this.

'use server'
import mongoose from 'mongoose';

If you are calling a Server Action in a Client Component then try the above code, it will work.

Check the link for detailed information.

EDIT :-

In basic Node.js projects, you can connect to the database in the entry file index.js and you don't call that again.But in Nextjs, there isn't any entry file. Because all the pages and route handlers are specific to the pages or API routes, you can use the experimental feature called instrumentation.

Enable the instrumentation feature by adding the code below to the next.config.js file.

module.exports = {
    experimental: {
        instrumentationHook: true,
    },
}

Create a new file instrumentation.js at the root of project or inside src directory if it exist. And add the code below.

import connect from 'path-to-your-database.js-file'

export async function register() {
    await connectToDB();
}

You just need to export the register function and call the connectToDB() function inside it.

If the connection is successful, you will see the message MongoDB is already connected in the console even before you access any page or api route.

For detailed information you can visit this [link][2] where you will get each & every aspect about how to connect with MongoDB using mongoose.

like image 172
Subha Avatar answered Aug 01 '26 09:08

Subha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!