这是我的.env
DB_DATABASE="xyz_datatbase"
DB_USERNAME="xyz_user"
DB_PASSWORD="xyz_password"
在index.js中,我使用的是上面的env const,但是我得到的错误密码即使是字符串也必须是字符串,我用typeof process.env.DB_PASSWORD进行了检查,然后我得到了字符串
// config.db.url = mongodb://localhost/
mongoose.connect(config.db.url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
dbName: process.env.DB_DATABASE || '',
auth: {
user: process.env.DB_USERNAME || '',
pass: process.env.DB_PASSWORD || '',
},
});
控制台错误
(node:28764) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: password must be a string
at NativeConnection.Connection.openUri (D:\test\test-app-node-js\node_modules\mongoose\lib\connection.js:830:32)
at Mongoose.connect (D:\test\test-app-node-js\node_modules\mongoose\lib\index.js:335:15)
at Object.<anonymous> (D:\test\test-app-node-js\server\server.js:10:10)
at Module._compile (internal/modules/cjs/loader.js:778:30)
答案 0 :(得分:2)
当您将数据或env变量存储在.env文件中时,请勿将其用双引号引起来,您的代码应像这样,
DB_DATABASE=xyz_datatbase
DB_USERNAME=xyz_user
DB_PASSWORD=xyz_password
答案 1 :(得分:1)
从documentation
您可以在顶级选项中指定user
和pass
,例如
// config.db.url = mongodb://localhost/
mongoose.connect(config.db.url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
dbName: process.env.DB_DATABASE || '',
user: process.env.DB_USERNAME || '',
pass: process.env.DB_PASSWORD || '',
});