Reputation: 10818
That is how I validating and saving my user:
var user = new User({ /** from body **/ });
user.validate((err) => {
if (err) {
console.log(err);
res.json({ success: false, message: 'Invalid input' });
}
else {
user.save((err) => {
if (err) { throw err; }
console.log(err);
res.json({ success: true });
});
}
});
Is there a better way of validate and save with mongoose with the less code lines or without if/else
?
Upvotes: 1
Views: 1257
Reputation: 525
You can also add your validations inside your schema. I will recommend this way because you'll be able to make custom validations depending of the field.
http://mongoosejs.com/docs/validation.html
Then you'll only need to save your user and check for an error inside the save callback method.
Upvotes: 1