tommyd456 tommyd456 - 3 days ago 6
Javascript Question

Validating user using .pre save

My API accepts

users
POSTed as JSON. I would like to validate certain fields only if they are included as part of the JSON object.

For example, a user might look like this:

{
"email" : "test@test.com",
"username" : "testing",
"name" : "Test User"
}


or it might not have a name field:

{
"email" : "test@test.com",
"username" : "testing"
}


and I would like to make sure
name
has at least 6 characters if it is an included field.

I'm trying to build the validation process into my model using
.pre
but things aren't quite as I'd expect them.

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 above code is for testing. Using either of the JSON objects above, the output is always "Name found" even though the object doesn't have a
name
property when I output to the console. Is this because the model has a
name
property?

Answer

You see the user object in the terminal and there is no property for name because the posted json might not have a name field as you mentioned, so you may do your logic/condition just when the name property is existed as follow:

UserSchema.pre('save', function(next) {
  if (this.name !== undefined) {
    if (this.name.length <= 6) {
      // throw error or whatever
    }
  }
  next();
});
Comments