node.js,MongoDB-异步和等待功能在findOne()函数中未按预期工作

时间:2018-10-28 05:58:42

标签: node.js mongodb async-await

我对node.js和MongoDB还是比较陌生,所以如果能很明显地回答这个问题,请提前抱歉。

我正在尝试创建逻辑来验证传入的对象,但是我在使用异步和等待时间正确计时方面遇到困难。基本上,我将传递一个字符串,并尝试查看该字符串中是否存在数据库中的任何记录。如果不存在,则errors返回空,如果存在,则errors包含某些内容。这是我的代码的相关部分:

模式(../ models / FriendRequest):

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var friendRequestSchema = new Schema({
    requestFrom: {type: String, required: true},
    requestTo: {type: String, required: true},
});

module.exports = mongoose.model('FriendRequest', friendRequestSchema);

逻辑:

var FriendRequest = require('../models/FriendRequest');

async function checkForDuplicateRecord(requestTo) {
    let errors = "";

    // do not allow duplicate requests
    FriendRequest.findOne({
        requestTo: requestTo
    }, (err, record) => {
        if (err) {
            errors += "{'\n'}Server Errors.";
        } else if (record) {
            errors += "{'\n'}You have already sent this person a friend request.";
        }
        console.log(record);
    })
    return await errors
}

// Function to perform server-side validation of the friend request before sending to db.
const FriendRequestValidator = (requestTo) => {
    let errors = "";
        (async() => {    
            let duplicationErrors = await checkForDuplicateRecord(requestFrom, requestTo);
            console.log('duplication errors: ' + duplicationErrors);
            errors += duplicationErrors;
        })()
    return errors;
};

module.exports = FriendRequestValidator;

当我打印record时,我发现records中的数据是否正确。但是,duplicateErrorsrecord之前被打印,并且即使record不为空也为空。这使我相信计时是我的结果未达到预期效果的原因,并且我使用了asyncawait错误。

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

以这种方式更改功能iostat

checkForDuplicateRecord

答案 1 :(得分:0)

await要求函数返回承诺。但是在您的情况下,您正在调用该函数并在回调函数中处理errors,因此在下一条语句中您将errors作为空字符串

async function checkForDuplicateRecord(requestTo) {
   let errors = "";
    try{
     let friendRequestSent = await FriendRequest.findOne({
        requestTo: requestTo
     });

     //If already sent request to same user throw error
     if(friendRequestSent)
        throw new Error("Your error message")

     //.... rest of code 

    }catch(err){
      //it will throw error if anything goes wrong in your findOne query or error thrown by your logic if request is sent to same user
      errors = err.message
    }
    return errors;
}