私はnode.js apiをビルドしており、エラーに関するメッセージだけをコールバックに渡したいと考えています。今私はここに私のコードは userModel.js私は「メッセージを検索フロントエンドに機能させることができます。もちろん、モデルからコントローラ(Mongoose)へのエラーメッセージのみを渡す方法は?
/* Custom Validation */
const validator = (v)=> {
return v.length > 5;
};
/* END of Custom Validation */
const UserSchema = new Schema({
username: {
type: String,
validate: [
validator,
'The Username is not long enough'
],
required: [true, 'The Username is required'],
unique: true,
lowercase: true
},
password: {
type: String,
required: [true, 'The Password is required']
},
email: {
type: String,
validate: [
(v)=> { return /^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i.test(v)},
'{VALUE} is not a valid email!'
],
lowercase: true,
required: true
},
role: {
type: [{
type: String,
enum: ['user', 'manager', 'admin']
}],
default: ['user']
},
team: {
type: [{
type: String,
enum: ['IHLO', 'ADULT&SH', 'IPJ', 'ISD', '']
}],
default: ['']
},
created_date: {
type: Date,
default: Date.now
},
});
UserSchema.pre('save', ...
UserSchema.methods.comparePassword = ...
module.exports = mongoose.model('Users', UserSchema);
**userController.js**
/Register new user
exports.signup = (req, res)=> {
let new_user = new User(req.body);
new_user.save((err, new_user)=> {
if (err)
return res.json({success: false, msg: err});
res.json({success: true, msg: `Successful created new user ${new_user.username}.`});
});
};
あるこの
{
"success": false,
"msg": {
"errors": {
"email": {
"message": "[email protected] is not a valid email!",
"name": "ValidatorError",
"properties": {
"type": "user defined",
"message": "{VALUE} is not a valid email!",
"path": "email",
"value": "[email protected]"
},
"kind": "user defined",
"path": "email",
"value": "[email protected]"
},
"username": {
"message": "The Username is not long enough",
"name": "ValidatorError",
"properties": {
"type": "user defined",
"message": "The Username is not long enough",
"path": "username",
"value": "te"
},
"kind": "user defined",
"path": "username",
"value": "te"
}
},
"_message": "Users validation failed",
"name": "ValidationError"
}
}
のようなオブジェクトとの契約を持っている必要がありますいくつかのレコードで100を超えるエラーが発生する可能性があります。とにかく私はそれをやり遂げることができ、冗長データを渡さないのですか?
返信いただきありがとうございますが、オブジェクトの解析を避けようとしています。 – user3315525
はこの場合のように見えます – user3315525