无法连接到MongoDB集群

时间:2019-10-10 18:49:03

标签: node.js mongodb

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

我无法连接到mongodb cluster0,出现错误 (node:22264) 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. TypeError: callback is not a function at $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'
}

2 个答案:

答案 0 :(得分:0)

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

{ useNewUrlParser: true, useUnifiedTopology: true }

还请确保您的连接字符串正确,并在读取后通过console.log(db)从config正确加载。

答案 1 :(得分:0)

如果连接到DBName,则需要在选项中提供Atlas

mongoose

.connect(db,
    {dbName: 'yourDbName', 
     useNewUrlParser: true ,
     useUnifiedTopology: true }
).then(() => console.log('MongoDB Connected'))

.catch(err => console.log(err));

和所有选项都在一个对象中。更多信息here