我面临此TypeError:当我使用nodejs
、express.js
、MongoDB
、mongoose
创建一个小应用程序时,当我将Express应用程序与mongoose连接时,当我替换密码时,遇到这种类型的错误,“无法读取未定义的属性”replace "”
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const app = require('./app');
dotenv.config({ path: './config.env' });
const DB = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => {
console.log(con.connections);
console.log('DB connection succesful!!');
});
const port = process.env.PORT || 3001;
app.listen(port, (req, res) => {
console.log(`App is running on ${port}...`);
});
如何解决此错误?
3条答案
按热度按时间uxhixvfz1#
这个问题通常是由于没有正确指定环境配置文件的路径引起的,请注意
dotenv.config({ path: './config.env' });
行,您正在当前文件夹中搜索config.env文件,请确保该文件在当前工作目录中存在,如果没有,请正确指定配置文件的路径,问题将立即得到解决。2ul0zpep2#
我得到了同样的错误,我通过更正config.env文件来解决,其中
数据库= mongodb+服务器:shailesh:@cluster0.n1pjr.mongodb.net/natours?retryWrites=true/majority?
我删除了true/即Majority后面的字符。
但是,如果这不能解决您的问题,则只需确保数据库已注册为环境变量。因为错误与应用程序无法找到名为“DATABASE”的环境变量的问题有关。
pbossiut3#
config.env
file, to check thatIf you access to
.env
now checkDATABASE
andDATABASE_PASSWORD
is mentioned correctly.2.1 to reset password of mongoDB Atlas cluster got to DATABASE ACCESS click on it now it will show your user, at right end click to edit.
2.2 now popup open, edit your password and save it. and got
config.env
file change it.config.env
file contain and check these should be written correctly. DATABASE url you get from atlas just copy and paste it just replace password to PASSWORD. thats it.