简体   繁体   中英

Docker - Nodejs to Mongodb connection works but collection is null

I am trying to connect from NodeJS Docker container to MongoDB Docker container. I can access the MongoDb from a client such as RoboMongo.

But in NodeJS it connects to the database but the db is null and I get an error when trying to get a collection.

 url = 'mongodb://127.0.0.1:27017/mydb';

router.get('/api/v1/test', function (req, res, next) {

      MongoClient.connect(url, function(err, db) {

          var collection = db.collection('myApptbl');   

       });
});

I am getting the below error in my docker logs.

/usr/src/myapp/node_modules/mongodb/lib/mongo_client.js:225
          throw err
          ^

TypeError: Cannot read property 'collection' of null

 at /usr/src/myapp/server.js:52:26
    at connectCallback (/usr/src/app/node_modules/mongodb/lib/mongo_client.js:315:5)
    at /usr/src/myapp/node_modules/mongodb/lib/mongo_client.js:222:11
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

Can you please help or provide suggestions on why I am getting this error.

Your connection string mongodb://127.0.0.1:27017/mydb is telling your NodeJS app connect to MongoDB in the same container by referencing 127.0.0.1 (localhost).

You want to tell it to connect to the MongoDB container, depending on how you've started your MongoDB container, with something like mongodb://mongodb:27017/mydb .

If you've started your containers with something like docker-compose , you should be able to use the name of the service:

...

services:

    mongodb: <--- you can use this in your connection string
        image: xxx

    your-node-app:
        image: xxx

If you're not using docker-compose and are using --link , you will need to reference the name of the link in your connection string.

Eg,

docker run -d --name mongodb mongodb

docker run -d --link mongodb:mongodb your-node-app

Note : The reason for this is because docker will add an entry to your /etc/hosts file that point the service name / link name to the private IP address of the linked container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM