首页 > 解决方案 > 尝试使用 mongoose 连接 mongodb 数据库时出现 MongooseServerSelectionError

问题描述

我们正在尝试将 AWS Lambda Node.js 函数连接到 VPC 中的 Mongodb 集群。

它适用于单个 IP,因此不存在与 AWS 相关的权限问题。

当我们使用下面的连接字符串进入猫鼬时。

const uri = 'mongodb://10.0.0.2:27001,10.0.0.3:27002/dbName?replicaSet=replicaSetName';

我们正在低于错误,

Response
{
  "errorType": "MongooseServerSelectionError",
  "errorMessage": "getaddrinfo ENOTFOUND mongo06.server",
  "trace": [
    "MongooseServerSelectionError: getaddrinfo ENOTFOUND mongo06.server",
    "    at NativeConnection.Connection.openUri (/opt/nodejs/node_modules/mongoose/lib/connection.js:844:32)",
    "    at Mongoose.createConnection (/opt/nodejs/node_modules/mongoose/lib/index.js:285:17)",
    "    at Runtime.exports.handler (/var/task/index.js:17:31)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
  ]
}

我正在使用下面的代码使用 mongoose 客户端连接 mongodb,

const mongoose = require("mongoose");
let conn = null;
const uri = 'mongodb://10.0.0.2:27001,10.0.0.3:27002/dbName?replicaSet=replicaSetName'

exports.handler = async function (event, context) {
    context.callbackWaitsForEmptyEventLoop = false;

    if (conn == null) {
        console.log(uri);

        conn = await mongoose.createConnection(uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            bufferCommands: false, // Disable mongoose buffering
            bufferMaxEntries: 0 // and MongoDB driver buffering
        });

        //connectionInstance connected
        conn.once('open', () => {
            console.info("MongoDb connected successfully");
        });
        mongoose.set('debug', true);

    }
    const M = conn.model('collectionName');
    const doc = await M.findOne();
    console.log(doc);
};

我需要帮助来解决这个问题。

标签: node.jsmongodbmongooselambda

解决方案


推荐阅读