I searched a lot about this, but none of them could help me.
When I run my project, I get this error:
/home/ali/Desktop/personalitytest-backend/node_modules/mongoose/lib/connection.js:428 throw new MongooseError('The
uri
parameter toopenUri()
must be a ' + ^ MongooseError: Theuri
parameter toopenUri()
must be a string, got "undefined". Make sure the first parameter tomongoose.connect()
ormongoose.createConnection()
is a string.
My index.js file:
const express = require('express'),
app = express(),
mongoose = require('mongoose'),
rateLimit = new require('express-rate-limit')({
windowMs: 1000 * 60 * 10,
max: 500,
handler: (req, res) => {
res.json({
data: 'Your request was too much, please try again in 10 minutes later.',
status: 'error'
})
}
});
const Application = new class {
constructor() {
this.setConfig();
this.setupDB();
this.setRouters();
this.setupExpress();
}
setConfig() {
require('dotenv').config();
app.use(require('helmet')());
app.use(express.json());
}
setupDB() {
mongoose.Promise = global.Promise;
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useCreateIndex: true });
}
setRouters() {
app.use('/', require('./routes'));
}
setupExpress() {
app.listen(process.env.PORT, () => console.log(`Listening on port ${process.env.PORT}.`));
// app.listen(process.env.PORT, process.env.IP, () => console.log(`Listening on port ${process.env.PORT}.`));
}
}
My .env file:
PORT=3000
DATABASE_URL=mongodb://localhost:27017/PersonalityTest
JWT_SECRETKEY=asfdawetq312etr%!@$qe
If I simply write database url in mongoose.connect method, there will be no error.
For example, this doesn't have error:
mongoose.connect("mongodb://localhost:27017/PersonalityTest", { useNewUrlParser: true, useCreateIndex: true });
Have you checked if your .env variables can be readed from that index.js file?
For example,check out what you get when you log some of them to the console:
console.log(process.env.DATABASE_URL);
If you get 'undefined', then you could try especifiying the absolute path for your .env file like this:
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, './.env') });
I struggled with this problem recently and in my case that solved the issue. Regards.
To read the .env
-file you'll need to install something that will read that file, for instance the dotenv
package
npm install dotenv --save
Then you require that package in your code
require('dotenv').config();
And according to the dotenv
documentation you should do it
As early as possible in your application, require and configure dotenv.
Next you might need to add double quotation marks around your DATABASE_URL
value
DATABASE_URL="mongodb://localhost:27017/PersonalityTest"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With