Search code examples
mongodbtypeormmongodb-atlas

Connecting to MongoDB Atlas with TypeOrm?


I am trying to connect to Mongodb Atlas with TypeOrm.

Here is my ormconfig.json :

{
  "type": "mongodb",
  "host": "cluster0-****.mongodb.net",
  "port": 27017,
  "username": "testUser",
  "password": "******",
  "database": "test",
  "useNewUrlParser": true,
  "synchronize": true,
  "logging": true,
  "entities": ["src/entity/*.*"]
}

And then when I try to createConnection() is get this error : (node:10392) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-****.mongodb.net:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND cluster0-****.mongodb.net cluster0-****.mongodb.net:27017]

Actually I can not find any information on how to do this.

Is my port right ? And if it is not where can I found it ? Where can I find my database name on Atlas ?


Solution

  • Ok I solved it by doing :

    {
      "type": "mongodb",
      "url": "mongodb+srv://testUser:<password>@cluster0-****.mongodb.net/test?retryWrites=true&w=majority",
      "useNewUrlParser": true,
      "synchronize": true,
      "logging": true,
      "entities": ["src/entity/*.*"]
    }
    

    I don't really know what was the issue with the "field by field" config but it seems to work fine by passing the url.