首页 > 解决方案 > 无法连接到mongodb集群

问题描述

我是节点 js 的新手。我正在开发简单的用户身份验证应用程序。

我无法连接到 mongodb cluster0,出现错误:

(node:22264) DeprecationWarning:当前的服务器发现和监控引擎已被弃用,并将在未来的版本中删除。要使用新的服务器发现和监控引擎,请将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。TypeError:回调不是 $initialConnection.$initialConnection.then.err 处的函数

我已经通过添加这个或{ useUnifiedTopology: true }仍然没有得到相同的错误来使用这两种方式

const express = require("express");
const expressLayouts = require("express-ejs-layouts");
const mongoose = require("mongoose");

const app = express();

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

//connect to mongodb
mongoose
  .connect(db, { useNewUrlParser: true }, { useUnifiedTopology: true })
  .then(() => console.log("MongoDB Connected"))
  .catch(err => console.log(err));

我的keys.js

module.exports = {
  MongoURI:
    "mongodb+srv://cluster0:<123455>@cluster0-7tt0p.mongodb.net/test?retryWrites=true&w=majority"
};

标签: node.jsmongodb

解决方案


您需要在单个对象中发送 useNewUrlParser 和 useUnifiedTopology。

{ useNewUrlParser: true, useUnifiedTopology: true }

还要确保您的连接字符串是正确的,并在阅读后通过 console.log(db) 从配置中正确加载。


推荐阅读