Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

validation returns false, but element still passes. Mongoose

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
                }
            },
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading