-1

I'm relatively new to node.js and MongoDB, so sorry in advance if it is an obvious answer.

I am trying to create the logic to validate an object that is being passed in, but I am having difficulty using async and await to time things correctly. Basically, I will be passing in a string and am trying to see if there is any record in the db that exists with that string. If there isn't, then errors returns empty, and if there is, then errors has something in it. Here are the relevant parts of my code:

The Schema (../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);

The Logic:

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;

When I print record, I see that if it exists, the data in records is correct. However, duplicateErrors is being printed before record, and is empty, even if record is not empty. This leads me to believe that the timing is the reason my results are not going as expected, and that I'm using async and await incorrectly.

Thank you very much in advance for any help!

marhami
  • 11
  • 4
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Oct 28 '18 at 05:59

2 Answers2

0

Change function checkForDuplicateRecord in this way

async function checkForDuplicateRecord(requestTo) {
    let errors = "";
    try{
        // do not allow duplicate requests
        let record = await FriendRequest.findOne({
                requestTo: requestTo
            });
        if (record) {
            errors += "{'\n'}You have already sent this person a friend request.";
            console.log(record);
        }
    }
    catch(e){
        errors += "{'\n'}Server Errors.";
    }
    return errors
}
Milad Aghamohammadi
  • 1,866
  • 1
  • 16
  • 29
0

await requires function to return the promise. But in your case you was calling the function and handling errors in callback function so you was getting errors as empty string in next statement.

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;
}
Juned Lanja
  • 1,466
  • 10
  • 21