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
CodePudding user response:
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...');
CodePudding user response:
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.