Reputation: 514
I have a Next.js app. I have an error with Mongodb. I couldn't solve this problem for a while. That's why I wanted ask you guys. I hope we can solve it. It's very important for me. Firstly I'll give you my server.js codes, after that I'll give you the error message from console.
Server.js file codes:
const express = require('express')
const next = require('next')
const mongoose = require('mongoose')
require('dotenv/config')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const port = process.env.SERVER_PORT || 3000
mongoose.connect(process.env.DATABASE,{
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('DB connected!')
const port = process.env.PORT || 3000
app.prepare().then(()=>{
const server = express()
//ROUTES
server.use(express.json())
server.get('*', (req, res) => handle(req, res))
server.listen(port, (err) => {
if(err) throw err
console.log(`Server listen on http://127.0.0.1:${port}`)
})
})
})
.catch((err) => {
console.log('DB ERROR:', err)
})
Error message on console:
DB ERROR: 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.
at NativeConnection.Connection.openUri (/home/ubuntu/nodeApps/mywebsite-next/node_modules/mongoose/lib/connection.js:684:11)
at /home/ubuntu/nodeApps/mywebsite-next/node_modules/mongoose/lib/index.js:332:10
at /home/ubuntu/nodeApps/mywebsite-next/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/ubuntu/nodeApps/mywebsite-next/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/ubuntu/nodeApps/mywebsite-next/node_modules/mongoose/lib/index.js:1158:10)
at Mongoose.connect (/home/ubuntu/nodeApps/mywebsite-next/node_modules/mongoose/lib/index.js:331:20)
at Object.<anonymous> (/home/ubuntu/nodeApps/mywebsite-next/server.js:11:10)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
I have the link of Mongodb in my env file. Maybe the error causes because of this situation?
DATABASE=mongodb+srv://myusername:[email protected]/mydbusername?retryWrites=true&w=majority
Upvotes: 0
Views: 3683
Reputation: 101
You should put your login credentials to your mongodb url code like this:
DATABASE=mongodb+srv://admin:[email protected]/<dbusername>?retryWrites=true&w=majority
If you did already try to give the path to dotenv:
require('dotenv').config({ path: 'ENV_FILENAME' });
Upvotes: 1