mongodb MongoError:拓扑已关闭,请在已建立数据库连接的情况下进行连接

blpfk2vs  于 2022-11-22  发布在  Go
关注(0)|答案(6)|浏览(131)

我正在写一个web应用程序,它使用异步数据库请求作为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");
});

控制台输出:
在唯一用户之前
true(应该是)
唯一用户之后
MongoError:拓扑已关闭。
创建用户:未定义的

***...***结束

以下是用于验证用户是否唯一的函数:

/*  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;
  }
}
k97glaaz

k97glaaz1#

我已经找到了问题的解决方案,但我不确定我是否理解其中的原因。validateUniqueUser函数的finally块中的client.close()。它在createPracticeProfile函数中的连接完成插入用户之前关闭了连接。
当那条线被取出来时,函数就起作用了。

nbysray5

nbysray52#

问题是客户端变量需要再次重新示例化,

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

尝试将其放在createPracticeProfile、validateUniqueUser和其他函数的开头

20jt8wwn

20jt8wwn3#

我收到错误

MongoError: Topology is closed

因为身份验证问题

MongoEror: Authentication failed

在我的例子中,问题出在我的数据库的password上。我的密码只包含数字。
我将密码更改为所有字符,两个错误都得到解决。

xienkqul

xienkqul4#

配置您的客户端连接,如下例所示

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();
});
fcwjkofz

fcwjkofz5#

在我的情况下-使用MongoClient连接到AtlasDB-我必须将访问集群的IP列入白名单

ss2ws0br

ss2ws0br6#

我想你的mongodb服务已经停止了,要启动它,请执行任务管理器-〉服务-〉Mongodb -〉右键单击-〉启动

相关问题