I have my model user.
// models/user.js
var mongoose=require("mongoose");
var Schema=mongoose.Schema;
var userSchema=new Schema({
name:{
type:String,
required:"Es necesario un nombre",
maxlength:[10,"Nombre muy largo max 10"]
},
lastName:{
type:String,
required:"Es necesario el apellido",
maxlength:[10,"Apellido muy largo"]
},
userName:{
type:String,
unique:true,
require:"Es necesario un username",
},
password:{
type:String,
require:"Es necesario un password",
validate:{
validator:function(pass){
if( this.password_confirmation!=undefined)
return this.password_confirmation==pass;
else{
return true;
}
},
message:"Las contraseñas son diferentes"
}
},
email:{
type:String,
require:"Es necesario un email"
}
})
userSchema.virtual("password_confirmation").get(function(){
return this.p_c
}).set(function(password){
this.p_c=password;
})
var User=mongoose.model("User",userSchema);
module.exports=User;
An endpoint to log in.
// routes/user.js
router.route("/login").get(login.login_get).post(login.login_post);
// login_post
var login_post=function(req,res,next){
if(!req.body.password || !req.body.userName){
res.send("Error");
}
User.findOne({userName:req.body.userName,password:req.body.password},function(err,us){
if(err)console.log(String(err));
console.log("Usuario encontra",us);
res.send(us);
});
}
What I want to do is the following, validate from the model before entering User.findOne, for example something like this.
var user=new User(req.body,function(err){
if(err)res.send("Error",String(err));
});
User.findOne({userName:user.userName,password:user.password},function(err,us){
if(err)console.log(String(err));
console.log("Usuario encontra",us);
res.send(us);
});
to avoid using this and validating from the model.
if(!req.body.password || !req.body.userName){
res.send("Error");
}
or else you can that way maybe something like that.
var validate=function(model,next){
if(//NO SE QUE IRIA PARA VALIDAR EL MODELO//){}
next("//Algo como los errores del modelo model.err//);
}
var user=new User(req.body);
validate(user,function(err){
if(err){
console.log(String(err));
res.send("Hubo un error validando los datos",err);
}
}
}
This is to be able to search for users, since to create it is not necessary to do something additional, because if it throws the errors that I have made.
Since when doing
User.findOne({userName:req.body.userName,password:req.body.password},function(err,us){
if(err)console.log(String(err));
console.log("Usuario encontra",us);
res.send(us);
});
without the validation it throws only that it did not find the user, and no error if for example I do not put password.
for dm
I did not know about DTO, when it comes to validate it looks good, so if I should create a DTO schema in specific cases, but what I was going to do is the following, what I was doing in my examples was to bring the error pull, which defined in the model since for example if I put something like
User.create(req.body,function(err,us){
if(err) console.log(String(err));
console.log(us);
});
This one does bring me the set of errors, for example if passwords do not match, or a field is missing, I wanted to do something like this for findOne , but this does not bring me the pull of errors (those defined in userSchema) to show them in a toast , but rather it does not detect any error, therefore it does not return anything.
With what you put to create a DTO I could do it, but the point is that I wanted to minimize the code that I put, in addition to the libraries, that's why my query.
If I missed the response codes, I still need to optimize the code better.
Here's an important difference: Normally the object/model you transport over the network is different from the one you store in the database. For example, you would never send the user's password when you reply to them for security reasons, nor would you allow them to change some properties of the record, such as an id that relates it to another entity, etc.
We usually call the objects that we store in the database as the MODEL, and the objects that we use to transfer data between nodes, the DTO (or Data Transfer Object).
Now, in Javascript due to its dynamism, it is not always necessary to create a separate model (the primary model will not work since it requires name, lastName, etc). It must be evaluated in each case. This case does not seem necessary, since it is two fields and easy to validate.
Alternatively, a lighter option than creating a Schema for UserDTO would be to use some lightweight schema validation library like indicative .
By the way, in the code you showed us there is nothing for when the user does not exist in the database or the password does not match (perhaps it was a simplified example, but I have taken it into account in the example)
Another change that I recommend you make is to use the appropriate response codes, that is 500, 401 and 400 depending on the case (see in the code)
Salu2
EDITION:
I understand what you say in your edition: Maybe the LOGIN example is not the best case because you never want to report the exact error, for security reasons. But since this is applicable to any entity, I tell you that indicative has another method.
Which returns an array with the list of errors/violations of the given schema. For what it serves to inform you.
It's your choice, I understand that adding another library is a difficult decision for many reasons, and this is just an alternative.
In my opinion it is a good alternative to your general problem, it allows you to do all kinds of validations, customize error messages, use templates and argue the error messages, it allows you to sanitize (aka sanitize) the input data and the documentation is It is based on examples and you can read it in 15-20 minutes.