Not able to connect to mongoose
Answered
<Milind ツ /> posted this in #help-forum
I am building a nextjs ecommerce and after adding mongoose and trying to connect to mongodb local server from api route, it throws:
my code:
⨯ src\utils\mongoHelper.ts (7:31) @ mongoDBUri
⨯ (0 , mongoose__WEBPACK_IMPORTED_MODULE_1__.createConnection) is not a function
5 |
6 | let mongoConnect = async () => {
> 7 | let client = createConnection(mongoDBUri);
my code:
import Product from "@/models/product";
import mongoose, { connect, connection, createConnection } from "mongoose";
const mongoDBUri = process.env.DB_URI as string;
let mongoConnect = async () => {
let client = createConnection(mongoDBUri);
if (client.readyState == 1) {
return;
}
await connect(mongoDBUri);
};
export default mongoConnect;
Answered by <Milind ツ />
turns out exporting a runtime config from api route that handles the mongo connection and retrive/post data breaks mongoose
// export const config = {
// runtime: "edge",
// };
9 Replies
if i remove the client part and call connection.readyState then throws cannot read undefined from readystate
turns out exporting a runtime config from api route that handles the mongo connection and retrive/post data breaks mongoose
// export const config = {
// runtime: "edge",
// };
Answer
Alligator mississippiensis
Hi @<Milind ツ /> , if you are still encountering with this problem, I can help you.
import mongoose from "mongoose";
const connect = async() => {
try {
await mongoose.connect(process.env.DATABASE_URL!, {
dbName:"<YOUR DB NAME>",
authSource:"admin"
});
console.log("MongoDB connection successfully established")
} catch(err){
throw new Error("Error occured while connecting mongodb");
}
}
export default connect;
you can use this approach too.
don't forget to remove dbName and authSource from your database URL
DATABASE_URL="mongodb+srv://admin:password@<cluster_name>.89234234.mongodb.net/"
Removing the edge runtime config from api route did the trick for me back then. Now I switched to prisma so not an issue anymore
I forgot to mark this answered hmm
Alligator mississippiensis
I am happy for ya! ðŸ‘