mongodb **错误***类型错误:无法读取未定义的属性'replace'

l7wslrjt  于 2022-12-11  发布在  Go
关注(0)|答案(3)|浏览(232)

我面临此TypeError:当我使用nodejsexpress.jsMongoDBmongoose创建一个小应用程序时,当我将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}...`);
});

如何解决此错误?

uxhixvfz

uxhixvfz1#

这个问题通常是由于没有正确指定环境配置文件的路径引起的,请注意dotenv.config({ path: './config.env' });行,您正在当前文件夹中搜索config.env文件,请确保该文件在当前工作目录中存在,如果没有,请正确指定配置文件的路径,问题将立即得到解决。

2ul0zpep

2ul0zpep2#

我得到了同样的错误,我通过更正config.env文件来解决,其中
数据库= mongodb+服务器:shailesh:@cluster0.n1pjr.mongodb.net/natours?retryWrites=true/majority?
我删除了true/即Majority后面的字符。
但是,如果这不能解决您的问题,则只需确保数据库已注册为环境变量。因为错误与应用程序无法找到名为“DATABASE”的环境变量的问题有关。

pbossiut

pbossiut3#

  1. Cannot read property because there is an error to read your config.env file, to check that
console.log(process.env);
// use thie before const DB to check file is accessible

If you access to .env now check DATABASE and DATABASE_PASSWORD is mentioned correctly.

  1. If everything is written correct then there is problem with your password to correct your password by customise it and don't use special character.
    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.
  2. IN 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.
NODE_ENV=development
PORT=8000
DATABASE=mongodb+srv://***USER_name***:<PASSWORD>@cluster0.awemngr.mongodb.net/***DATABASENAME***?retryWrites=true&w=majority
DATABASE_PASSWORD= your_password

相关问题