バージョン
MongoDB: 3.0.7
mongoose: 4.3.6
ビルトインバリデータ
String
enum
: リストにない値をはじく
var SakeSchema = new Schema({
sakeType: {
type: String,
enum: ['Junmai', 'Ginjo']
// 'Junmai'はOK
// 'JunmaiDaiGinjo'はエラー
}
});
match
: 正規表現にマッチしない値をはじく
var SakeSchema = new Schema({
sakeType: {
type: String,
match: /\.*Junmai\.*/
// 'JunmaiGinjo'はOK
// 'Ginjo'はエラー
}
});
maxlength
, minlength
: 最大,最小文字数
var SakeSchema = new Schema({
sakeType: {
type: String,
maxlength: 10,
minlength: 2
// 'Junmai'はOK
// 'TokubetsuJunmai'はエラー
}
});
Number
max
, min
: 最大,最小値
var SakeSchema = new Schema({
alcoholContent: {
type: Number,
max: 21,
min: 0
// 21はOK
// 0はOK
// 22はエラー
// -1はエラー
}
});
共通
全てのスキーマタイプで使えるバリデータに、required
, unique
がある。それぞれ必須制約とユニーク制約をかけるバリデータ。
var SakeSchema = new Schema({
brand: {
type: String,
required: true, // 空文字はエラーになる
unique: true
}
});
カスタムバリデータ
ビルトインバリデータでは不十分な場合に独自にバリデータを作ることができる。
自分が作ったバリデータを紹介。
Emailバリデータ
var emailValidator = {
validator: function(v) {
var pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return pattern.test(v);
},
message: '`{VALUE}` is invalid syntax of `{PATH}`'
}
var UserSchema = new Schema({
email: {
type: String,
validate: emailValidator
}
});
数値バリデータ(0以上の整数)
var positiveIntegerValidator = {
validator: function(v) {
var pattern = /^([1-9]\d*|0)$/;
return pattern.test(v);
},
message: '`{VALUE}` is invalid value. `{PATH}` should be a positive integer'
}
var SakeSchema = new Schema({
polishingRate: {
type: Number,
max: 100,
min: 0,
validate: positiveIntegerValidator
// 0-100の整数以外はエラー
}
});
配列サイズバリデータ
var arrayLengthValidator = function(len) {
return {
validator: function(v) {
return v.length <= len;
},
message: '`{PATH}` can be stored up to ' + len
}
}
var SakeSchema = new Schema({
pictureUrl: {
type: [{
type: String
}],
validate: arrayLengthValidator(10)
// 写真のURLは10個まで保存可能
}
});
プラグイン
スキーマはプラガブルになっていて、公開されているプラグインを使ってスキーマを拡張することができるようになっている。
便利なプラグインを一つ紹介。
mongoose-id-validatorは参照制約をチェックするバリデータで、参照先ドキュメントが存在しない場合にエラーを出してくれる。
var idValidator = require('mongoose-id-validator');
// 参照バリデータを全てのスキーマに適用
mongoose.plugin(idValidator);
var SakeSchema = new Schema({
customer: {
type: Schema.Types.ObjectId,
ref: 'Customer'
// 'Customer'コレクションに存在しないObjectIdを指定したらエラー
}
});