Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
43 views
in Technique[技术] by (71.8m points)

javascript - Unable to connect to direct database

I am using mongo via Docker in a Node application.
Able to connect to mongo directly if I use the following connection String.

mongodb://root:example@localhost:27017

What this does is if I were to create a collection, it ends up in a database called test
which I did not create. From what I searched around, this db name test is a default.

Seen examples where the connection String should include the database name as follows:

mongodb://root:example@localhost:27017/my_actual_db

But trying to connect in this manner, it complains that my username/password is no longer correct.
Unable to see how that is possible since am using the root password plus it works if I
don't mention a DB in the connection String.

Could I please get some help on this.
1. My question is why the username/password no longer works. Is there an issue with my docker-compose file?
2. Else is there a way I could change the db name via mongoose?
Looking at docs, I attempted to change it via the options as follows but it doesn't make a diff.
The db is still called test.

My docker-compose.yml file

version: "3.1"

services:
  mongo:
    image: mongo
    container_name: mongo-instance-1
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

    volumes:
      - ./data:/data/db

  mongo-express:
    image: mongo-express
    container_name: mongo-express-instance-1
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example

Connecting via mongoose in node app.

// process.env.DB_CONNECTION is the connection Strings above
mongoose.connect(process.env.DB_CONNECTION,
  {
    useNewUrlParser: true,
    name: 'my_actual_db', // doesn't make a diff, db name remains as test
  })
  .then(value => {
    console.log(value)
  })
  .catch(err => {
    console.log(err)
  })
question from:https://stackoverflow.com/questions/65865144/unable-to-connect-to-direct-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...