mongoose 尽管凭据正确,MongoDB身份验证仍失败

eimct9ow  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(189)

我今天遇到了一个奇怪的问题。我似乎无法从我的Node.js后端连接到我的本地MongoDB容器进行本地测试。
下面是我创建容器的方法:

docker start mongo || docker run --rm --name mongo -e MONGO_INITDB_ROOT_USERNAME=\"$MONGODB_USER\" -e MONGO_INITDB_ROOT_PASSWORD=\"$MONGODB_PASSWORD\" -e MONGO_INITDB_DATABASE=\"concept_slide\" -p 27017:27017 -d mongo:latest

我知道我的应用程序和数据库使用相同的凭据,因为它们从相同的环境变量中提取:

export const connectMongoDB = () => {
  console.log({
    user: process.env.MONGODB_USER,
    pass: process.env.MONGODB_PASSWORD,
  });
  mongoose.connect(`mongodb://${process.env.MONGODB_TEST_HOSTNAME}:27017/concept_slide`, {
    user: process.env.MONGODB_USER,
    pass: process.env.MONGODB_PASSWORD,
    hostname: process.env.MONGODB_TEST_HOSTNAME,
  });

  mongoose.connection
    .on('connected', () => {
      console.log('Local database connected');
    })
    .on('error', (err) => {
      console.error(
        'Local database unreachable. Please check database or network access. Error: ',
        err
      );
    });
};

下面是错误消息:

Local database unreachable. Please check database or network access. Error:  MongoServerError: Authentication failed.
    at Connection.onMessage (/Users/fareskissoum/Documents/Personal-Projects.tmp/open-concepts/open-concepts-backend/node_modules/mongodb/lib/cmap/connection.js:207:30)
    at MessageStream.<anonymous> (/Users/fareskissoum/Documents/Personal-Projects.tmp/open-concepts/open-concepts-backend/node_modules/mongodb/lib/cmap/connection.js:60:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (/Users/fareskissoum/Documents/Personal-Projects.tmp/open-concepts/open-concepts-backend/node_modules/mongodb/lib/cmap/message_stream.js:132:20)
    at MessageStream._write (/Users/fareskissoum/Documents/Personal-Projects.tmp/open-concepts/open-concepts-backend/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at Socket.ondata (node:internal/streams/readable:766:22)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed',
  [Symbol(errorLabels)]: Set(1) { 'HandshakeError' }

我甚至尝试在控制台中打印它们,以确定是否存在问题,我确认没有:

{ user: 'fares', pass: 'password', hostname: 'localhost' } // printed

我不明白问题从何而来。我觉得我错过了什么。

bkhjykvo

bkhjykvo1#

我真的需要停止编码这么晚。
结果发现问题是数据库(concept_slide)在创建容器/示例时不存在,因此没有要连接的内容。
这是我的无知和缺乏更清晰的文件的混合。

相关问题