'how to connect mongodb
Im not sure how to get my mongodb connected and I keep getting this error what should I change?
[email protected] start > node --experimental-modules --es-module-specifier-resolution=node index.js
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. Failed to connect database
Listening on PORT 5000
my index.js file:
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
// Importing the routes
import authRoute from "./routes/authRoute";
const app = express();
dotenv.config({ path: "./config.env" });
app.use(cors());
app.use(express.json());
// All the routes
app.use("/api", authRoute);
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log("Database connected successfully");
})
.catch((err) => {
console.log(`${err} Failed to connect database`);
});
const PORT = process.env.PORT || 5000;
// Listening to port
app.listen(PORT, () => {
console.log(`Listening on PORT ${PORT}`);
});
Solution 1:[1]
You can use this:
const mongoose = require("mongoose");
mongoose.connect(
process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on("error", (err) => {
console.log("err", err);
});
mongoose.connection.on("connected", (err, res) => {
console.log("MongoDB connected successfully!");
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sagar |
