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!