【问题标题】:Unable to connect MongoDB in Node JS application无法在 Node JS 应用程序中连接 MongoDB
【发布时间】:2020-03-31 06:54:12
【问题描述】:

我的应用程序运行良好,并在开发一个简单的节点 js 应用程序时连接到 mongoDB。但突然它开始显示这个错误。这是控制台的快照:

这是我提供 mongoURI 的文件,在出错之前它工作得很好:

module.exports = {
  mongoURI:
    "mongodb+srv://glorious:glorious@cluster0-to57n.mongodb.net/test?retryWrites=true&w=majority"
};

这是我的 server.js 文件:

const express = require("express");
const mongoose = require("mongoose");

const app = express();

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(db)
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

app.get("/", (req, res) => res.send("Hello World"));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`));

这是我的 package.json 文件:

{
  "name": "devconnector",
  "version": "1.0.0",
  "description": "A social network for developers",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js"
  },
  "author": "Utkarsh Shrivastava",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "gravatar": "^1.8.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.7.13",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "validator": "^12.1.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.1"
  }
}

【问题讨论】:

标签: javascript node.js mongodb web


【解决方案1】:

useNewUrlParser doc:

useNewUrlParser 选项

默认情况下,mongoose.connect() 会打印出以下警告:

DeprecationWarning: current URL string parser is deprecated, and will
be removed in a future version. To use the new parser, pass option {
useNewUrlParser: true } to MongoClient.connect.

MongoDB Node.js 驱动程序重写了它用来解析 MongoDB 连接字符串的工具。因为这是一个如此大的变化,他们将新的连接字符串解析器放在一个标志后面。要打开此选项,请将useNewUrlParser 选项传递给mongoose.connect()mongoose.createConnection()

mongoose.connect(uri, { useNewUrlParser: true });
mongoose.createConnection(uri, { useNewUrlParser: true }); 

您还可以设置全局useNewUrlParser 选项以默认为每个连接打开useNewUrlParser

// Optional. Use this if you create a lot of connections and don't
want // to copy/paste `{ useNewUrlParser: true }`.
mongoose.set('useNewUrlParser', true); 

要使用{useNewUrlParser: true } 测试您的应用,您只需检查您的应用是否连接成功。一旦 Mongoose 成功连接,URL 解析器就不再重要了。如果您无法与{ useNewUrlParser: true } 联系,请在 GitHub 上打开一个问题。

useUnifiedTopology doc:

useUnifiedTopology

默认情况下,mongoose.connect() 会打印出以下警告:

DeprecationWarning: current Server Discovery and Monitoring engine is
deprecated, and will be removed in a future version. To use the new
Server Discover and Monitoring engine, pass option {
useUnifiedTopology: true } to the MongoClient constructor. 

Mongoose 5.7 使用 MongoDB 驱动程序 3.3.x,它引入了一个重要的重构,即它如何处理监控副本集中的所有服务器或 分片集群。在 MongoDB 中,这被称为服务器 发现和监控。

要选择使用新的拓扑引擎,请使用以下行:

mongoose.set('useUnifiedTopology', true); 

如果您发现任何意外 行为,请在 GitHub 上打开一个问题。

所以你需要将两个选项都传递给mongoose.connect

// Connect to MongoDB
mongoose
  .connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
  ...

【讨论】:

【解决方案2】:

您的server.js 文件

const express = require('express');
const connectDB = require('./config/db');
const app = express();
// connect Database
connectDB();
app.get('/', (req, res) => res.send('API Running...'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started On Port ${PORT}`));

db.js 文件夹下的config 文件

const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');

const connectDB = async () => {
  try {
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('MongoDB Connected !!');
  } catch (err) {
    console.error(err.message);
    // Exit process
    process.exit(1);
  }
};

module.exports = connectDB;

配置文件夹下的default.json

{
  "mongoURI": mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
}

您可以查看更多信息 Connection String URI Formatdefault.json

【讨论】:

    【解决方案3】:

    您缺少 URL 解析器。 只需将您的代码修改为

    ...rest of the code
    
    // Connect to MongoDB
    mongoose
      .connect(db, {newUrlParser: true})
      .then(() => console.log("MongoDB Connected"))
      .catch(err => console.log(err));
    
    ...rest of the code
    

    或者您也可以使用全局设置它

    mongoose.set('useNewUrlParser', true);
    

    在此处了解更多信息 https://mongoosejs.com/docs/deprecations.html

    【讨论】:

      【解决方案4】:

      我刚刚与 Mondo DB 合作过。 此代码可能会有所帮助

      在连接到 MongoDb 时添加 {useNewUrlParser:true}。参见 Mongo DB deprecations

      你的 server.js 文件:

      const express = require("express");
      const mongoose = require("mongoose");
      
      const app = express();
      
      // DB Config
      const db = require("./config/keys").mongoURI;
      
      // Connect to MongoDB
      mongoose
        .connect(db, { useNewUrlParser: true })
        .then(() => console.log("MongoDB Connected"))
        .catch(err => console.log(err));
      
      app.get("/", (req, res) => res.send("Hello World"));
      
      const port = process.env.PORT || 5000;
      
      app.listen(port, () => console.log(`Server running on port ${port}`));
      

      希望这项工作正常,并将连接您的 mongo db。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-10
        • 2020-03-22
        • 2017-06-07
        • 2019-02-19
        相关资源
        最近更新 更多