无法连接Node.js应用程序与MongoDB Atlas



我已经在MongoDBAtlas中创建了一个新的集群,但我不能连接我的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'
}

服务器运行成功。我的应用在连接到阿特拉斯之前是正常的。我重新从头创建了一个新的集群,以便我可以确保在创建集群时没有犯任何错误。

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}🎈.......`);
});

。文件/p>

NODE_ENV=devlopment
PORT=8000
USERNMAE=IrfanAsif
DATABASE_PASSWORD=zAC8yIHLJIegJHSQ
DATABASE=mongodb+srv://irfan:<PASSWORD>@cluster0.onw2w.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

所以首先我没有看到任何特殊的理由保持数据库连接字符串之外的密码,因为它是在。env变量,所以它不会有任何机会对最终用户可用,或任何人没有访问服务器文件。

对于您的问题,您可以将process .env. database和密码记录到控制台,以确保它正确打印出来吗?既然你的回调和promise resolve似乎没有问题,这应该是配置问题。

最新更新