0

I'm not able to solve MongoParseError.

First my I tried this

mongoose.connect(`mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});

resulting in this error

MongoParseError: Unescaped slash in userinfo section

Then I escaped all the slashes

mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});

and I ended up in this error which I'm not able to solve

MongoParseError: Invalid connection string

This is my index.js

'use strict';

const mongoose = require('mongoose');
mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('ok');
});

const express = require('express');

// Constants
const PORT = 8080;
const HOST = 'localhost';


var kittySchema = new mongoose.Schema({
  name: String
});

var Kitten = mongoose.model('Kitten', kittySchema);

var silence = new Kitten({ name: 'Test1234' });


// App
const app = express();
app.get('/', (req, res) => {
  res.send(silence.name);
});

app.listen(PORT);
console.log(`Running on http://${HOST}:${PORT}`);

And here's the docker-compose.yml

version: '3.7'
services:
  web:
    build: .
    command: npm start
    volumes:
      - ./src:/usr/app/
      - ./src/node_modules:/usr/app/node_modules
    ports:
      - 80:8080
    environment:
      DB_NAME: websitedb
      DB_USER: /run/secrets/db_user
      DB_PASSWORD: /run/secrets/db_password
    secrets:
      - db_user
      - db_password
  db:
    image: mongo:latest
    volumes:
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_DATABASE: websitedb
      MONGO_INITDB_ROOT_USERNAME_FILE: /run/secrets/db_user
      MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_user
      - db_password
volumes:
  mongo:
secrets:
  db_user:
    file: ./db_user.txt
  db_password:
    file: ./db_password.txt

Can anyone tell me what I'm doing wrong?

  • What’s with the backticks instead of single quotation marks? – Philᵀᴹ May 30 at 8:49
  • @Philᵀᴹ they're template literals – Glorfindel May 30 at 9:02
  • Thanks. Learn something new every day :-) – Philᵀᴹ May 30 at 9:15
0

Try printing the result of mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME} in console and use the result to connect to mongodb through mongo shell.

Also, post the final result with masked details for review.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.