【问题标题】:Getting error while connecting to mongoDB database using Node.js使用 Node.js 连接到 mongoDB 数据库时出错
【发布时间】:2020-01-12 02:04:56
【问题描述】:

使用 Node.js 连接 MLAB 中的 mongoDB 数据库时出现以下错误。

Error in DB connection : {
  "name": "MongoNetworkError",
  "errorLabels": [
    "TransientTransactionError"
  ]
}

这是我的代码:

var mongoose = require('mongoose');
const authData =  {
    "useNewUrlParser": true,
    "useCreateIndex": true
};
//connecting local mongodb database named test
mongoose.connect(
  'mongodb://subhra:*****@ds139989.mlab.com:39989/hlloyd',
  {useCreateIndex: true, useNewUrlParser: true,useUnifiedTopology: true },
  (err)=>{
    if (!err) 
      console.log('MongoDB connection succeeded.');
    else 
      console.log('Error in DB connection : ' + JSON.stringify(err, undefined, 2));
  }
);

module.exports = mongoose;

这里我的数据库存在于MLAB 中,但是当我试图连接到该数据库时,它向我抛出了那个错误。我需要在这里连接到我的数据库。

【问题讨论】:

标签: node.js mongodb mongoose mlab


【解决方案1】:

"useCreateIndex": trueuseUnifiedTopology: true 已弃用。



试试下面的代码来连接你的 mongoDB 数据库。

mongoose.connect('mongodb://subhra:*****@ds139989.mlab.com:39989/hlloyd', {useNewUrlParser: true})
.then(() => console.log("Connected"))
.catch(err => console.log(err));

module.exports = mongoose;

【讨论】:

    【解决方案2】:

    请在MongoDB网站的“主页>安全部分>网络访问>添加IP”之后将您当前的IP或0.0.0.0添加到白名单中。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 1970-01-01
      • 2020-09-08
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多