programing

Mongo 오류:토폴로지가 닫혔습니다. 데이터베이스 연결이 설정되었지만 연결하십시오.

iphone6s 2023. 7. 11. 21:39
반응형

Mongo 오류:토폴로지가 닫혔습니다. 데이터베이스 연결이 설정되었지만 연결하십시오.

저는 API의 일부로 비동기 데이터베이스 요청을 사용하는 웹 애플리케이션을 작성하고 있습니다.현재 비동기 함수에서 함수 반환을 기다리는 비동기식 고속 경로가 있습니다.이 두 함수 모두 부울을 반환하고 데이터베이스를 쿼리합니다.하나는 제대로 작동하지만 두 번째는 작동하지 않습니다.

MongoClient 설정은 다음과 같습니다.

const MongoClient = require('mongodb').MongoClient;
const uri = config.uri;                         // Contains custom url for accessing database
const client = new MongoClient(uri, { useUnifiedTopology: true}, { useNewUrlParser: true }, { connectTimeoutMS: 30000 }, { keepAlive: 1});

여기서 config는 파일에서 가져온 것입니다.

const config = require("./config.js");

제대로 작동합니다.

고속 설정은 다음과 같습니다.

app.post("/signup", async function(request, response) {
  log("POST request at /signup");

  log("BEFORE UNIQUE USER");
  const isUniqueUser = await validateUniqueUser(request.body.email, request.body.password);
  log(isUniqueUser);
  const status = {
    status: null
  };
  if (isUniqueUser) {
    log("AFTER UNIQUE USER");
    let userCreated = await createPracticeProfile(request.body.email, request.body.password);
    log("user created: " + userCreated);
    if (userCreated) {
      status.status = "user_created";
    }
    response.json(status);
  } else {
    response.json(status);
  }

  console.log("********************************end");
});

콘솔 출력:

고유 사용자 이전

참(그래야 할)

고유 사용자 이후

Mongo 오류:토폴로지가 닫혔습니다.

사용자가 생성됨: 정의되지 않음

***...***끝

사용자가 고유한지 확인하는 기능은 다음과 같습니다.

/*  VALIDATE_UNIQUE_USER
USE: ensure user does not have existing profile
PARAMS: email (string), password (string)
RETURN: isUniqueUser (bool)
*/
async function validateUniqueUser(email, password) {
  // connect to database
  const database = await client.connect().catch(err => {
    log("ERROR while connecting to database at: validateUniqueUser");
    console.log(err);
    client.close();
  });

  // database connection failed
  if (!database) {
    return false;
  }

  // connection successful => find user
  let user;
  try {
    user = await database.db("guitar-practice-suite").collection("users").findOne({email: email});
  } catch(err) {
    log("ERROR while finding user in database at: validateUniqueUser");
    console.log(err);
    client.close();
    return false;
  } finally {
    client.close();
    // user not found (unique)
    if (user === null || user === undefined) {
      return true;
    }
    return false;
  }
}

컬렉션에 사용자를 삽입하는 기능은 다음과 같습니다.

/* CREATE_PRACTICE_PROFILE
USE: insert a practice profile into the database
PARAMS: email (string), password (string)
RETURN: userCreated (bool)
*/
async function createPracticeProfile(email, password) {
  // hash password
  let hashedPassword;
  try {
    hashedPassword = await new Promise((resolve, reject) => {
      bcrypt.hash(password, null, null, function(err, hash) {
        if (err) {
          reject(err);
        }
        resolve(hash)
      });
    });
  } catch(err) {
    log("ERROR while hashing password at: createPracticeProfile");
    console.log(err);
    return false;
  }

  // connect to database
  const database = await client.connect().catch(err => {
    log("ERROR while connecting to database at: validateUniqueUser");
    console.log(err);
    client.close();
  });

  // database connection failed
  if (!database) {
    return false;
  }

  // database connection successful => insert user into database
  let insertUserToUsers;
  let insertUserToExercises;
  let insertUserToCustomExercises;
  try {
    insertUserToUsers = await database.db("guitar-practice-suite").collection("users").insertOne({email: email, password: hashedPassword});
    insertUserToExercises = await database.db("guitar-practice-suite").collection("exercises").insertOne({email: email});
    insertUserToCustomExercises = await database.db("guitar-practice-suite").collection("custom-exercises").insertOne({email: email, exercises: []});
  } catch(err) {
    log("ERROR while inserting user into database at: createPracticeProfile");
    console.log(err);
    client.close();
    return false;
  } finally {
    client.close();
    return insertUserToUsers && insertUserToExercises && insertUserToCustomExercises;
  }
}

저는 그 문제에 대한 해결책을 찾았지만, 그 추론을 이해할 수 있을지 확신할 수 없습니다.client.close()ValidateUniqueUser 함수의 마지막 블록에 있습니다.createPracticeProfile 함수의 연결이 사용자 삽입을 끝내기 전에 연결을 닫는 중이었습니다.

그 선을 빼면, 그 기능이 작동합니다.

문제는 클라이언트 변수를 다시 인스턴스화해야 한다는 것입니다.

const client = new MongoClient(uri, { useUnifiedTopology: true}, { useNewUrlParser: true }, { connectTimeoutMS: 30000 }, { keepAlive: 1});

이것을 createPracticeProfile의 시작에 넣고 UniqueUser 및 기타 함수를 검증해 보십시오.

오류가 발생했습니다.

MongoError: Topology is closed

인증 문제 때문에

MongoEror: Authentication failed

저의 경우, 문제는password내 데이터베이스의.제 비밀번호는 숫자만 포함되어 있었습니다.

저는 비밀번호를 모든 문자로 변경했고 두 가지 오류가 모두 해결되었습니다.

아래 예제와 같이 클라이언트 연결 구성

var MongoClient = require('mongodb').MongoClient;

var Server = require('mongodb').Server;

var mongoClient = new MongoClient(new Server('localhost', 27017));

mongoClient.open(function(err, mongoClient) {

  var db1 = mongoClient.db("mydb");

  mongoClient.close();
});

제 경우 - MongoClient를 사용하여 AtlasDB에 연결 - 클러스터에 액세스하는 IP를 화이트리스트에 추가해야 했습니다.

mongodb 서비스가 중지된 것 같습니다. 시작하려면 작업 관리자 -> 서비스 -> Mongodb -> 오른쪽 클릭 -> 시작

내 코드는 오랫동안 잘 작동했으며 이전에는 이 오류를 발생시키지 않았습니다.MongoError: Topology is closed.

하지만 제 노트북이 장시간 켜져 있고 다른 프로젝트를 동시에 개발하고 있었기 때문에 메인 프로젝트는 터미널에서 실행하고 있었습니다.mongo데이터베이스에 대한 연결 중 하나를 닫지 않고 다른 연결을 병렬로 열어 일종의 충돌을 일으켰을 가능성이 높습니다.

일반적으로, 저의 경우, 컴퓨터를 다시 시작하는 것이 도움이 되었고 비슷한 오류가 다시 발생하지 않았습니다.

언급URL : https://stackoverflow.com/questions/59942238/mongoerror-topology-is-closed-please-connect-despite-established-database-conn

반응형