I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object.
For example, a user object could contain:
{
"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79687e794d79687e79236e6260">[email protected]</a>",
"username" : "testing",
"name" : "Test User"
}
or it might not include the name field:
{
"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="522637212612263721267c313d3f">[email protected]</a>",
"username" : "testing"
}
In cases where the name
field is present, I want to ensure it has at least 6 characters.
I'm attempting to implement this validation process within my model using the .pre
method, but I'm encountering unexpected results.
var UserSchema = new Schema({
id : String,
name : String,
email : String,
username : String
},{ timestamps: { createdAt: 'created_at',updatedAt: 'updated_at' } });
UserSchema.pre('save', function(next) {
console.log(this); //no evidence of name property here
if("name" in this){
console.log("Name found"); //this is always the output
} else {
console.log("Name not found");
}
next();
});
The provided code snippet serves for testing purposes. However, even with the given JSON objects, the output consistently shows "Name found," despite the absence of the name
property when checking the console. Could this behavior be influenced by the presence of the name
property in the model?