我正在编写一个使用异步数据库请求作为api一部分的web应用程序.目前,我有一个异步快速路由,等待异步函数返回函数.这两个函数都返回布尔值,并且都查询数据库.一个能正常工作,但第二个不能.

以下是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("唯一用户之前");
  const isUniqueUser = await validateUniqueUser(request.body.email, request.body.password);
  log(isUniqueUser);
  const status = {
    status: null
  };
  if (isUniqueUser) {
    log("唯一用户之后");
    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");
});

控制台输出:

唯一用户之前

是的(应该是这样)

唯一用户之后

MongoError:拓Flutter 已关闭.

用户创建:未定义

***...***终止

以下是验证用户是否唯一的功能:

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

推荐答案

我已经找到了解决问题的办法,但我不确定我是否理解其中的道理.

当这条线被取出时,该功能就起作用了.

Mongodb相关问答推荐

mongoose正在抛出Schema的错误has';t已在next.js中注册

错误起草的 MongoDB 聚合管道 $match 阶段

映射数组导致 mongodb 聚合

Pymongo API TypeError: Unhashable dict

是否可以迭代 mongo 游标两次?

加载时将 mongo 存储的日期转换回自 Unix 纪元以来的毫秒数?

MongoDB 聚合 $divide 计算字段

如何在 mongo JavaScript shell 中中止查询

spring-data-mongo - 可选查询参数?

在 mongodb 的一次更新调用中推送到两个单独的数组

如何在mongodb中删除数组的第n个元素

Django admin 和 MongoDB,可能吗?

mongodb nodejs - 转换圆形 struct

mongo - Ruby连接问题

在 MongoDB 中为现有用户更改密码

mongoose:按字母顺序排序

Meteor订阅不更新集合的排序顺序

从 mongo 结果中删除 _id

AsQueryable 方法是否在新的 Mongodb C# 驱动程序 2.0rc 中离开?

有没有办法防止 MongoDB 向集合名称添加复数形式?