Search code examples
javascriptnode.jsmongodbmongoose

How to resolve MongooseServerSelectionError: Invalid message size when connecting to MongoDB?


I'm encountering an issue when trying to connect to my MongoDB database using Mongoose in a Node.js application. The error message I'm receiving is:

Database can't be connected MongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864

This error seems to be related to the maximum allowed message size for MongoDB. According to the error, the message size being sent is 1347703880 bytes, which exceeds the maximum allowed size of 67108864 bytes (64 MB).

Here's the relevant code where I'm connecting to MongoDB using Mongoose:

app.config.js

const MONGO_DB_CONFIG = {
    DB: "mongodb://localhost:27017/ecommerce",
}

module.exports = {
    MONGO_DB_CONFIG,
};

index.js


const express = require("express");
const app = express();
const mongoose = require("mongoose");
const { MONGO_DB_CONFIG } = require("./config/app.config");
const errors = require("./middleware/errors");

mongoose.Promise = global.Promise;
mongoose.connect(MONGO_DB_CONFIG.DB, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(
    () => {
        console.log("Database Connected");
    },
    (error) => {
        console.log("Database can't be connected " + error);
    }
);

// ... (rest of the code)

I've checked that the MongoDB connection string (mongodb://localhost:27017/ecommerce) is correct, and I'm not sure what might be causing this "Invalid message size" error.

I've also tried updating my MongoDB and Mongoose versions, but the issue persists. Here are the versions I'm currently using:

  • MongoDB version: 6.0.4 
  • Mongoose version: 6.4.4

Can someone please guide me on how to resolve this MongooseServerSelectionError and successfully connect to my MongoDB database?


Solution

  • Usually I use the following for mongodb connection:

    mongoose.connect("mongodb://127.0.0.1:27017/ecommerce", {}, () => console.log("..."));
    

    Could you try this with a simple node index.js?

    I think mongoose.Promise = global.Promise is legacy, also using mongodb port for your server (process.env.port || 27017) seems weird