【问题标题】:Can not connect Node.js app with MongoDB Atlas无法将 Node.js 应用程序与 MongoDB Atlas 连接
【发布时间】:2021-10-02 06:50:12
【问题描述】:

我在 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

【问题讨论】:

  • 您确定已为您的集群创建了数据库用户吗?请确保您已替换 Atlas DB 路径中的正确值:将 、 和 替换为正确的凭据。 mongodb+srv://&lt;user&gt;:&lt;password&gt;@cluster0-nnezr.mongodb.net/&lt;dbname&gt;?retryWrites=true&amp;w=majority

标签: node.js mongodb express mongoose mongodb-atlas


【解决方案1】:

所以首先我看不出有什么特别的理由将密码保存在数据库连接字符串之外,因为它在 .env 变量中,所以最终用户或任何没有密码的人都不会有任何机会访问服务器文件。

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

【讨论】:

  • 这是我的导师编写的代码,现在可以使用了,感谢您的帮助
猜你喜欢
  • 2022-01-18
  • 2020-09-18
  • 2020-11-08
  • 2021-05-13
  • 2020-08-24
  • 2019-10-17
  • 1970-01-01
  • 2020-12-09
  • 2021-11-09
相关资源
最近更新 更多