Search code examples
node.jsmongodbmongoose

Can I connect Mongoose to a sharded MongoDB instance?


Using [email protected], I want to connect to a sharded MongoDB instance.

const url = "mongodb://user:pass@localhost:27022,localhost:27023/db";

// This never resolves
Mongoose.connect(url, (err, db) => {
    ...
});

When I make the connection using the native [email protected] library (the same version used by Mongoose), it works.

const url = "mongodb://user:pass@localhost:27022,localhost:27023/db";

// This resolves a connection
MongoClient.connect(url, (err, db) => {
    ...
});

When I make the connection in Mongoose, the connect callback never resolves.

Is there something in Mongoose that I have to configure to allow me to connect to a sharded Mongo instance?

Thanks


Solution

  • Need to pass an object in as the second argument, with the value mongos = true

    const url = "mongodb://user:pass@localhost:27022,localhost:27023/db";
    
    // This now resolves
    Mongoose.connect(url, { mongos: true }, (err, db) => {
        ...
    });
    

    It's not terribly clear from the docs, but it is there - http://mongoosejs.com/docs/connections.html