Good Day, So here is what I'm trying to do, I'm attempting to validate a username and confirm there is no other usernames in the database, and I think I'd found a solution. I believe I am returning false into the validator but the response still posts to the database. If I need to provide more let me know
const userSchema = new Mongoose.Schema (
{
playerName : {
type: String,
required: (true, "No Name Specified"),
validate: {
validator(val) {
value = true
User.findOne( { "playerName" : val}, function(err, result) {
if (result != null) {
value = false
}
})
return value
},
message: "playerName already Exsits"
}
},
Thank you in advance
CodePudding user response:
The problem is your validator is not waiting to the response and is reaching return value
(which is true) before the callback value = false
.
So you need an async
validator like this:
const userSchema = new Mongoose.Schema({
playerName: {
type: String,
required: (true, "No Name Specified"),
validate: {
async validator(val) {
const result = await User.findOne({
"playerName": val
})
return result == null ? true : false
},
message: "playerName already Exsits"
}
},