我已经在mongodb atlas中创建了一个新集群,但我无法将node.js应用程序与之连接。我是后端新手,正在学习mongodb。
Error: querySrv ENODATA _mongodb._tcp.cluster0.onw2w.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:206:19) {
errno: undefined,
code: 'ENODATA',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0.onw2w.mongodb.net'
}
服务器正在成功运行。在连接到atlas之前,我的应用程序正在运行。我从一开始就再次创建了一个新集群,这样我可以确保在创建集群时没有出错。
server.js文件
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,
useUnifiedTopology: true,
})
.then((con) => console.log('DB connection successful🍾....'))
.catch((error) => console.log(error));
const tourSchema = new mongoose.Schema({
// to specify a schema for our model
name: {
type: String,
require: [true, 'A tour must have a name'], // validator
unique: true,
},
rating: {
type: Number,
require: 4.5,
},
price: {
type: Number,
require: [true, 'A tour must have a price'],
},
});
const Tour = mongoose.model('Tour', tourSchema);
const testTour = new Tour({
// it is an instance of the tour model
name: 'The forest Hiker',
rating: 4.7,
price: 497,
});
testTour
.save() // this will save the data in the Tour collection in the database it will return a promise
.then(doc => console.log(doc))
.catch(err=> console.log('error: ', err))
const port = process.env.PORT || 8000;
app.listen(port, '127.0.0.1', () => {
console.log(`server running on port ${port}🎈.......`);
});
.env文件
NODE_ENV=devlopment
PORT=8000
USERNMAE=IrfanAsif
DATABASE_PASSWORD=zAC8yIHLJIegJHSQ
DATABASE=mongodb+srv://irfan:<PASSWORD>@cluster0.onw2w.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
1条答案
按热度按时间8cdiaqws1#
因此,首先,我不认为有任何特殊的理由将密码保留在db连接字符串之外,因为它位于.env变量中,所以最终用户或无法访问服务器文件的任何人都无法使用它。
对于您的问题,您是否可以将proccess.env.database和密码登录到console,以确保其正确输出?因为您的回调和承诺解析似乎是正确的,所以应该是配置问题。