#node.js #mongodb #docker #mongoose
#node.js #mongodb #докер #мангуст
Вопрос:
У меня проблемы с моей конфигурацией docker-mongodb. Когда я пытаюсь получить доступ к моей коллекции mongodb через mongoose, mongo возвращает следующую ошибку:
(base) c27gc@c27gc-desktop:~/Documentos/Code/Development/bloomtasks$ node usecases/get.js
Testing Connection...
Connection Error: MongoError: Authentication failed.
at MessageStream.messageHandler (/home/c27gc/Documentos/Code/Development/bloomtasks/node_modules/mongodb/lib/cmap/connection.js:268:20)
at MessageStream.emit (events.js:315:20)
at processIncomingData (/home/c27gc/Documentos/Code/Development/bloomtasks/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
at MessageStream._write (/home/c27gc/Documentos/Code/Development/bloomtasks/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:719:22)
at Socket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at Socket.Readable.push (internal/streams/readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
ok: 0,
code: 18,
codeName: 'AuthenticationFailed'
}
Файл get.js
'use strict';
const mongoose = require('mongoose');
const Repository = require('../Interfaces/repository.js')
const Task = require('../models/task.js');
const User = require('../models/user.js');
const date = require('date-and-time');
const path = 'mongodb://username:password@localhost:27017/dbname'
const repository = new Repository(path)
const now = new Date();
repository.create(Task, {
name: "My Name",
description: "Test String",
project: "My Project's Name",
difficulty: 2,
startDate: date.format(now, 'ddd, MMM DD YYYY'),
maxDevelopmentTime: 10,
expirationDate: date.format(now, 'ddd, MMM DD YYYY'),
comments: "String",
deliveryDate: date.format(now, 'ddd, MMM DD YYYY'),
assigned: false,
priority: 1,
reward: 15,
technologies: ["React", "Nodejs"]
})
Определение репозитория классов:
'use strict';
const mongoose = require('mongoose');
class Repository {
constructor(path){
mongoose.connect(path, {useNewUrlParser: true, useUnifiedTopology: true});
console.log("Testing Connection...")
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'Connection Error:'));
}
create(model, payload) {
model.create(payload)
mongoose.connection.close()
}
}
module.exports = Repository
Когда я изменяю следующую строку get.js
const path = 'mongodb://username:password@localhost:27017/dbname'
для
const path = 'mongodb://username:password@localhost:27017/'
Это создает базу данных с именем «test» и внутри нее коллекцию «tasks». Я считаю, что эта ошибка, вероятно, вызвана моей настройкой docker-mongodb.
настройка docker-mongodb:
docker-compose.yml
version: "3.8"
services:
database:
image: 'mongo'
container_name: 'mongo-test'
environment:
- MONGO_INITDB_DATABASE=dbname
- MONGO_INITDB_ROOT_USERNAME=username
- MONGO_INITDB_ROOT_PASSWORD=password
volumes:
- ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
- ./mongodata:/data/db
ports:
- '27017-27019:27017-27019'
init-mongo.js
первая попытка:
databases = ['dbname']
for (var i = databases.length - 1; i >= 0; i--) {
db = db.getSiblingDB(databases[i])
db.createUser({
user: "username",
pwd: "password",
roles: ["readWrite"]
})
}
вторая попытка:
db.createUser({
user: "username",
pwd: "password",
roles: [
{
"role" : "readWrite",
"db" : "dbname"
}]
})
Может быть, init-mongo.js файл не был восстановлен.
Спасибо за вашу помощь.