I just connected mongoDB using mongoose.
But I got error TypeError: Cannot read properties of undefined (reading 'split')
How can I fix this error?
Here’s my code
export const dbConnect = async () => {
mongoose.connect(process.env.NEXT_PUBLIC_MONGO_URI);
const db = mongoose.connection;
db.on('error', function () {
console.log('db connection failed!');
});
db.once('open', function () {
console.log('db connected!');
});
};
And I am using mongoose version 6.5.3, next version 12.2.5
4
Answers
What is value of process.env.NEXT_PUBLIC_MONGO_URI
Format should be like
mongoose.connect(‘mongodb://localhost/myapp’);
mongoose.connect(‘mongodb://username:password@host:port/database?options…’);
I think the problem will be in the connect function. The URI you give in might be wrong. Try logging it our before the function, to make sure it’s a correct uri.
https://www.mongodb.com/docs/manual/reference/connection-string/
Here you can find the correct connection string format.
If the error appears in the browser, it means that you are trying to use Mongoose in your client side code.
In fact, somewhere in its code, Mongoose checks for the version of the node installation it’s using.
Being ran in the browser, there is no such thing as
process.versions.node
, hence the error.Mongoose is packed in the final client bundle, hence the error comes from there and it doesn’t say much about where you have the wrong
import
/require
in your code.One strategy is to search for
"mongoose"
(including the double quotes) in your code, and remove theimport
/require
from all the files that are meant to be run in the client.TL;DR
Use a dynamic import. instead of:
Try:
See the docs here: Dynamic Imports
Why does this work?
Luca was correct to say the following:
To expand on that,
node.js
is not available on the client side of a next.js project, but it is available where server-side code runs such asgetServerSideProps
or/pages/api
. I assume you only want to use this function inside the/pages/api
folder and in that case it should work just fine.