Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 807
Anatole Lucet Avatar asked Jun 27 '19 16:06

Anatole Lucet


People also ask

Can you use TypeORM with MongoDB?

TypeORM has basic MongoDB support.

Why MongoDB Atlas is not connecting?

Check that you are using the correct username and password for your database user, and that you are connecting to the correct database deployment. Check that you are specifying the correct authSource database in your connection string.


2 Answers

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.

like image 187
Anatole Lucet Avatar answered Sep 26 '22 15:09

Anatole Lucet


The TYPEORM documentation is not so clear on mongodb connection issues, and maybe not updated frequently with. So I'm dropping this here for future readers.

  1. You need to make sure that your IP is whitelisted. (You can do so by going to project => network access [tab] => IP whitelist [tab] and add your ip address or use 0.0.0.0.
  2. Enable SSL for your connection by setting ssl:true in your orm config file.
  3. Don't forget to add your authentication database using authSource:admin.

Below is an example of my .env file

TYPEORM_CONNECTION=mongodb
TYPEORM_HOST=cluster0-shard-00-02-xxxxx.mongodb.net
TYPEORM_PORT=27017
TYPEORM_USERNAME=root
TYPEORM_PASSWORD=password
TYPEORM_DATABASE=mydatabase
TYPEORM_SYNCHRONIZE=true
TYPEORM_LOGGING=true
TYPEORM_ENTITIES=./dist/**/*.entity.js
TYPEORM_DRIVER_EXTRA={"ssl":true, "authSource": "admin"}
like image 42
Akinjiola Toni Avatar answered Sep 22 '22 15:09

Akinjiola Toni