SchemaType
SchemaType()
SchemaType.cast()
SchemaType.checkRequired()
SchemaType.get()
SchemaType.prototype.cast()
SchemaType.prototype.castFunction()
SchemaType.prototype.default()
SchemaType.prototype.doValidate()
SchemaType.prototype.get()
SchemaType.prototype.getEmbeddedSchemaType()
SchemaType.prototype.immutable()
SchemaType.prototype.index()
SchemaType.prototype.isRequired
SchemaType.prototype.path
SchemaType.prototype.ref()
SchemaType.prototype.required()
SchemaType.prototype.select()
SchemaType.prototype.set()
SchemaType.prototype.sparse()
SchemaType.prototype.text()
SchemaType.prototype.transform()
SchemaType.prototype.unique()
SchemaType.prototype.validate()
SchemaType.prototype.validateAll()
SchemaType.prototype.validators
SchemaType.set()
SchemaType()
パラメータ
path
«String»[options]
«SchemaTypeOptions» SchemaTypeOptions ドキュメントを参照してください[instance]
«String»
SchemaType コンストラクタ。SchemaType
を直接インスタンス化しないでください。Mongoose はスキーマパスを自動的に SchemaType に変換します。
例
const schema = new Schema({ name: String });
schema.path('name') instanceof SchemaType; // true
SchemaType.cast()
パラメータ
caster
«Function|false» 任意の値をこの型にキャストする関数。キャストに失敗した場合はエラーをスローします。
戻り値
- «Function»
任意の値をこの型にキャストするために使用される関数を取得/設定します。
例
// Disallow `null` for numbers, and don't try to cast any values to
// numbers, so even strings like '123' will cause a CastError.
mongoose.Number.cast(function(v) {
assert.ok(v === undefined || typeof v === 'number');
return v;
});
SchemaType.checkRequired()
パラメータ
[fn]
«Function» 設定した場合、現在設定されている関数を上書きします。
戻り値
- «Function» 入力された
fn
または既に設定されている関数
checkRequired
関数を設定/取得します。必須バリデーターが値が required
チェックをパスするかどうかをチェックするために使用する関数をオーバーライドします。個々の SchemaType でこれをオーバーライドします。
例
// Use this to allow empty strings to pass the `required` validator
mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
SchemaType.get()
パラメータ
getter
«Function»
戻り値
- «this»
このスキーマ型のすべてのインスタンスにゲッターをアタッチします。
例
// Make all numbers round down
mongoose.Number.get(function(v) { return Math.floor(v); });
SchemaType.prototype.cast()
パラメータ
value
«Object» キャストする値doc
«Document» キャストをトリガーするドキュメントinit
«Boolean»
Mongoose が任意の値をこの SchemaType にキャストするために呼び出す関数。
SchemaType.prototype.castFunction()
パラメータ
caster
«Function|false» 任意の値をこの型にキャストする関数。キャストに失敗した場合はエラーをスローします。
戻り値
- «Function»
任意の値をこの特定のスキーマタイプインスタンスにキャストするために使用される関数を取得/設定します。SchemaType.cast()
をオーバーライドします。
例
// Disallow `null` for numbers, and don't try to cast any values to
// numbers, so even strings like '123' will cause a CastError.
const number = new mongoose.Number('mypath', {});
number.cast(function(v) {
assert.ok(v === undefined || typeof v === 'number');
return v;
});
SchemaType.prototype.default()
パラメータ
val
«Function|any» 設定するデフォルト値
戻り値
- «Any,undefined,void» 設定されたデフォルト値を返します。
この SchemaType のデフォルト値を設定します。
例
const schema = new Schema({ n: { type: Number, default: 10 })
const M = db.model('M', schema)
const m = new M;
console.log(m.n) // 10
デフォルトは、デフォルトとして使用する値を返す 関数
か、リテラル値自体にすることができます。どちらの場合も、ドキュメント作成中に設定される前に、値はスキーマ型に基づいてキャストされます。
例
// values are cast:
const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
const M = db.model('M', schema)
const m = new M;
console.log(m.aNumber) // 4.815162342
// default unique objects for Mixed types:
const schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default(function () {
return {};
});
// if we don't use a function to return object literals for Mixed defaults,
// each document will receive a reference to the same object literal creating
// a "shared" object instance:
const schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default({});
const M = db.model('M', schema);
const m1 = new M;
m1.mixed.added = 1;
console.log(m1.mixed); // { added: 1 }
const m2 = new M;
console.log(m2.mixed); // { added: 1 }
SchemaType.prototype.doValidate()
パラメータ
value
«Any»callback
«Function»scope
«Object»[options]
«Object»[options.path]
«String»
戻り値
- «Any» バリデーターがない場合は、
fn
を呼び出した出力が返されます。それ以外の場合は何も返しません
この SchemaType に宣言されたバリデーターを使用して value
のバリデーションを実行します。
SchemaType.prototype.get()
パラメータ
fn
«Function»
戻り値
- «SchemaType» これ
このスキーマタイプにゲッターを追加します。
例
function dob (val) {
if (!val) return val;
return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
}
// defining within the schema
const s = new Schema({ born: { type: Date, get: dob })
// or by retreiving its SchemaType
const s = new Schema({ born: Date })
s.path('born').get(dob)
ゲッターを使用すると、生の mongodb ドキュメントから表示される値へのデータの表現を変換できます。
クレジットカード番号を保存していて、最後の 4 桁を除くすべてを mongoose ユーザーに隠したいとします。次の方法でゲッターを定義することで、それを実現できます。
function obfuscate (cc) {
return '****-****-****-' + cc.slice(cc.length-4, cc.length);
}
const AccountSchema = new Schema({
creditCardNumber: { type: String, get: obfuscate }
});
const Account = db.model('Account', AccountSchema);
Account.findById(id, function (err, found) {
console.log(found.creditCardNumber); // '****-****-****-1234'
});
ゲッターには 2 番目の引数として、ゲッターが定義されたスキーマタイプも渡されます。これにより、スキーマで渡されたオプションに基づいて調整された動作が可能になります。
function inspector (val, priorValue, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return schematype.path + ' is not';
}
}
const VirusSchema = new Schema({
name: { type: String, required: true, get: inspector },
taxonomy: { type: String, get: inspector }
})
const Virus = db.model('Virus', VirusSchema);
Virus.findById(id, function (err, virus) {
console.log(virus.name); // name is required
console.log(virus.taxonomy); // taxonomy is not
})
SchemaType.prototype.getEmbeddedSchemaType()
埋め込みスキーマ型がある場合は、それを返します。配列、ドキュメント配列、およびマップの場合、getEmbeddedSchemaType()
は配列の要素(またはマップの要素)のスキーマ型を返します。他の型の場合、getEmbeddedSchemaType()
は undefined
を返します。
例
const schema = new Schema({ name: String, tags: [String] });
schema.path('name').getEmbeddedSchemaType(); // undefined
schema.path('tags').getEmbeddedSchemaType(); // SchemaString { path: 'tags', ... }
SchemaType.prototype.immutable()
パラメータ
bool
«Boolean»
戻り値
- «SchemaType» これ
参照
このパスを不変として定義します。Mongoose は、親ドキュメントに isNew: true
がない限り、不変パスの変更を防ぎます。
例
const schema = new Schema({
name: { type: String, immutable: true },
age: Number
});
const Model = mongoose.model('Test', schema);
await Model.create({ name: 'test' });
const doc = await Model.findOne();
doc.isNew; // false
doc.name = 'new name';
doc.name; // 'test', because `name` is immutable
Mongoose は、厳密モードに基づいて、updateOne()
および updateMany()
を使用した不変プロパティの変更も防ぎます。
例
// Mongoose will strip out the `name` update, because `name` is immutable
Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
// If `strict` is set to 'throw', Mongoose will throw an error if you
// update `name`
const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
then(() => null, err => err);
err.name; // StrictModeError
// If `strict` is `false`, Mongoose allows updating `name` even though
// the property is immutable.
Model.updateOne({}, { name: 'test2' }, { strict: false });
SchemaType.prototype.index()
パラメータ
options
«Object|Boolean|String|Number»
戻り値
- «SchemaType» これ
このスキーマタイプのインデックスオプションを宣言します。
例
const s = new Schema({ name: { type: String, index: true })
const s = new Schema({ name: { type: String, index: -1 })
const s = new Schema({ loc: { type: [Number], index: 'hashed' })
const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
s.path('my.path').index(true);
s.path('my.date').index({ expires: 60 });
s.path('my.path').index({ unique: true, sparse: true });
注記
インデックスは、デフォルトでバックグラウンドで作成されます。background
が false
に設定されている場合、MongoDB はインデックスの構築が完了するまで、送信した読み取り/書き込み操作を実行しません。Mongoose のデフォルトをオーバーライドするには、background: false
を指定します。
SchemaType.prototype.isRequired
型
- «property»
この SchemaType に必須バリデーターがある場合は true。それ以外の場合は false。
例
const schema = new Schema({ name: { type: String, required: true } });
schema.path('name').isRequired; // true
schema.path('name').required(false);
schema.path('name').isRequired; // false
SchemaType.prototype.path
型
- «property»
スキーマ内のこの SchemaType へのパス。
例
const schema = new Schema({ name: String });
schema.path('name').path; // 'name'
SchemaType.prototype.ref()
パラメータ
ref
«String|Model|Function» モデル名、モデル、またはモデル名またはモデルを返す関数のいずれか。
戻り値
- «SchemaType» これ
このパスが参照するモデルを設定します。これは、populate がクエリする必要がある外部コレクションを決定するために参照するオプションです。
例
const userSchema = new Schema({ name: String });
const User = mongoose.model('User', userSchema);
const postSchema = new Schema({ user: mongoose.ObjectId });
postSchema.path('user').ref('User'); // Can set ref to a model name
postSchema.path('user').ref(User); // Or a model class
postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name
postSchema.path('user').ref(() => User); // Or a function that returns the model class
// Or you can just declare the `ref` inline in your schema
const postSchema2 = new Schema({
user: { type: mongoose.ObjectId, ref: User }
});
SchemaType.prototype.required()
パラメータ
required
«Boolean|Function|Object» バリデーターを有効/無効にするか、必須のブール値を返す関数、またはオプションオブジェクト[options.isRequired]
«Boolean|Function» バリデーターを有効/無効にするか、必須のブール値を返す関数[options.ErrorConstructor]
«Function» カスタムエラーコンストラクター。コンストラクターは、バリデータープロパティを含むオブジェクトを 1 つのパラメーターとして受け取ります。[message]
«String» オプションのカスタムエラーメッセージ
戻り値
- «SchemaType» これ
参照
- カスタマイズされたエラーメッセージ
- SchemaArray#checkRequired
- SchemaBoolean#checkRequired
- SchemaBuffer#checkRequired
- SchemaNumber#checkRequired
- SchemaObjectId#checkRequired
- SchemaString#checkRequired
この SchemaType に必須バリデーターを追加します。バリデーターは、unshift()
を使用してこの SchemaType のバリデーター配列の先頭に追加されます。
例
const s = new Schema({ born: { type: Date, required: true })
// or with custom error message
const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
// or with a function
const s = new Schema({
userId: ObjectId,
username: {
type: String,
required: function() { return this.userId != null; }
}
})
// or with a function and a custom message
const s = new Schema({
userId: ObjectId,
username: {
type: String,
required: [
function() { return this.userId != null; },
'username is required if id is specified'
]
}
})
// or through the path API
s.path('name').required(true);
// with custom error messaging
s.path('name').required(true, 'grrr :( ');
// or make a path conditionally required based on a function
const isOver18 = function() { return this.age >= 18; };
s.path('voterRegistrationId').required(isOver18);
必須バリデーターは、SchemaType の checkRequired
関数を使用して、指定された値が必須バリデーターを満たしているかどうかを判断します。デフォルトでは、値が val != null
の場合 (つまり、値が null でも undefined でもない場合)、必須バリデーターを満たしています。ただし、ほとんどの組み込み mongoose スキーマ型は、デフォルトの checkRequired
関数をオーバーライドします
SchemaType.prototype.select()
パラメータ
val
«Boolean»
戻り値
- «SchemaType» これ
このパスのデフォルトの select()
動作を設定します。
このパスを結果に常に含める場合は true
に、デフォルトで除外する場合は false
に設定します。この設定は、クエリレベルでオーバーライドできます。
例
T = db.model('T', new Schema({ x: { type: String, select: true }}));
T.find(..); // field x will always be selected ..
// .. unless overridden;
T.find().select('-x').exec(callback);
SchemaType.prototype.set()
パラメータ
fn
«Function»
戻り値
- «SchemaType» これ
このスキーマタイプにセッターを追加します。
例
function capitalize (val) {
if (typeof val !== 'string') val = '';
return val.charAt(0).toUpperCase() + val.substring(1);
}
// defining within the schema
const s = new Schema({ name: { type: String, set: capitalize }});
// or with the SchemaType
const s = new Schema({ name: String })
s.path('name').set(capitalize);
セッターを使用すると、生の mongodb ドキュメントまたはクエリに到達する前にデータを変換できます。
ウェブサイトのユーザー登録を実装しているとします。ユーザーはメールアドレスとパスワードを提供し、それが mongodb に保存されます。メールアドレスは、1 つのメールアドレスが複数のアカウントを持つことを避けるために、小文字に正規化する必要がある文字列です。たとえば、そうでない場合、avenue@q.com は、avenue@q.com と AvEnUe@Q.CoM を介して 2 つのアカウントに登録できます。
Mongoose セッターを使用して、メールアドレスの小文字正規化を簡単に設定できます。
function toLower(v) {
return v.toLowerCase();
}
const UserSchema = new Schema({
email: { type: String, set: toLower }
});
const User = db.model('User', UserSchema);
const user = new User({email: 'AVENUE@Q.COM'});
console.log(user.email); // 'avenue@q.com'
// or
const user = new User();
user.email = 'Avenue@Q.com';
console.log(user.email); // 'avenue@q.com'
User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'
上記のように、セッターを使用すると、MongoDB に保存する前、またはクエリを実行する前にデータを変換できます。
注:独自の関数を定義する代わりに、組み込みの lowercase: true
SchemaType オプションを使用することもできました。
new Schema({ email: { type: String, lowercase: true }})
セッターには 2 番目の引数として、セッターが定義されたスキーマタイプも渡されます。これにより、スキーマで渡されたオプションに基づいて調整された動作が可能になります。
function inspector (val, priorValue, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return val;
}
}
const VirusSchema = new Schema({
name: { type: String, required: true, set: inspector },
taxonomy: { type: String, set: inspector }
})
const Virus = db.model('Virus', VirusSchema);
const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
console.log(v.name); // name is required
console.log(v.taxonomy); // Parvovirinae
また、セッターを使用してドキュメントの他のプロパティを変更することもできます。ドキュメントでプロパティ name
を設定している場合、セッターは this
がドキュメントとして実行されます。注意してください。mongoose 5 では、セッターは this
がクエリとして name
でクエリを実行する場合にも実行されます。
const nameSchema = new Schema({ name: String, keywords: [String] });
nameSchema.path('name').set(function(v) {
// Need to check if `this` is a document, because in mongoose 5
// setters will also run on queries, in which case `this` will be a
// mongoose query object.
if (this instanceof Document && v != null) {
this.keywords = v.split(' ');
}
return v;
});
SchemaType.prototype.sparse()
パラメータ
bool
«Boolean»
戻り値
- «SchemaType» これ
スパースインデックスを宣言します。
例
const s = new Schema({ name: { type: String, sparse: true } });
s.path('name').index({ sparse: true });
SchemaType.prototype.text()
パラメータ
bool
«Boolean»
戻り値
- «SchemaType» これ
フルテキストインデックスを宣言します。
例
const s = new Schema({ name : { type: String, text : true } })
s.path('name').index({ text : true });
SchemaType.prototype.transform()
パラメータ
fn
«Function»
戻り値
- «SchemaType» これ
ドキュメントを JSON に変換するときに、このパスを変換するためのカスタム関数を定義します。
Mongoose は、1 つのパラメーター (パスの現在の value
) を使用してこの関数を呼び出します。Mongoose は、JSON 出力で戻り値を使用します。
例
const schema = new Schema({
date: { type: Date, transform: v => v.getFullYear() }
});
const Model = mongoose.model('Test', schema);
await Model.create({ date: new Date('2016-06-01') });
const doc = await Model.findOne();
doc.date instanceof Date; // true
doc.toJSON().date; // 2016 as a number
JSON.stringify(doc); // '{"_id":...,"date":2016}'
SchemaType.prototype.unique()
パラメータ
bool
«Boolean»
戻り値
- «SchemaType» これ
一意のインデックスを宣言します。
例
const s = new Schema({ name: { type: String, unique: true } });
s.path('name').index({ unique: true });
注:制約に違反すると、Mongoose のバリデーションエラーではなく、保存時に MongoDB から E11000
エラーが返されます。
SchemaType.prototype.validate()
パラメータ
obj
«RegExp|Function|Object» バリデーター関数、またはオプションを記述するハッシュ[obj.validator]
«Function» バリデーター関数。バリデーター関数がundefined
または true の値を返す場合、バリデーションは成功します。もし、falsey (undefined
を除く) を返すか、エラーをスローすると、バリデーションは失敗します。[obj.message]
«String|Function» オプションのエラーメッセージ。関数の場合、エラーメッセージを文字列として返す必要があります。[obj.propsParameter=false]
«Boolean» true の場合、Mongoose は、バリデータープロパティオブジェクト (validator
関数、message
などを含む) を、バリデーター関数の 2 番目の引数として渡します。多くのバリデーターが位置引数に依存しているため、この設定を有効にすると外部バリデーターで予測不可能な動作が発生する可能性があるため、これはデフォルトで無効になっています。[errorMsg]
«String|Function» オプションのエラーメッセージ。関数の場合、エラーメッセージを文字列として返す必要があります。[type]
«String» オプションのバリデータータイプ
戻り値
- «SchemaType» これ
このドキュメントパスのバリデーターを追加します。
バリデーターは、常に検証する値を最初の引数として受け取り、Boolean
を返す必要があります。false
を返すか、エラーをスローすると、バリデーションが失敗したことを意味します。
エラーメッセージの引数はオプションです。渡されない場合は、デフォルトの汎用エラーメッセージテンプレートが使用されます。
例
// make sure every value is equal to "something"
function validator (val) {
return val === 'something';
}
new Schema({ name: { type: String, validate: validator }});
// with a custom error message
const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
new Schema({ name: { type: String, validate: custom }});
// adding many validators at a time
const many = [
{ validator: validator, message: 'uh oh' }
, { validator: anotherValidator, message: 'failed' }
]
new Schema({ name: { type: String, validate: many }});
// or utilizing SchemaType methods directly:
const schema = new Schema({ name: 'string' });
schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');
エラーメッセージテンプレート
以下は、サポートされているテンプレートキーワードのリストです
- PATH:エラーがトリガーされているスキーマパス。
- VALUE:エラーをトリガーしている PATH に割り当てられた値。
- KIND:エラーをトリガーしたバリデーションプロパティ。例:必須。
- REASON:エラーの原因となったエラーオブジェクト(存在する場合)。
Mongoose の組み込みエラーメッセージテンプレートでは不十分な場合、Mongoose は message
プロパティを関数に設定することをサポートしています。
schema.path('name').validate({
validator: function(v) { return v.length > 5; },
// `errors['name']` will be "name must have length 5, got 'foo'"
message: function(props) {
return `${props.path} must have length 5, got '${props.value}'`;
}
});
Mongooseのエラーメッセージをバイパスして、バリデーターがスローするエラーメッセージをそのままコピーするには、以下のようにします。
schema.path('name').validate({
validator: function() { throw new Error('Oops!'); },
// `errors['name'].message` will be "Oops!"
message: function(props) { return props.reason.message; }
});
非同期バリデーション
MongooseはPromiseを返すバリデーターをサポートしています。Promiseを返すバリデーターは非同期バリデーターと呼ばれます。非同期バリデーターは並行して実行され、validate()
はすべての非同期バリデーターが完了するまで待機します。
schema.path('name').validate({
validator: function (value) {
return new Promise(function (resolve, reject) {
resolve(false); // validation failed
});
}
});
非同期バリデーターは、データベースから他のドキュメントを取得して検証したり、他のI/Oバウンドな検証ニーズを満たすために使用できます。
バリデーションはpre('save')
時、または手動でdocument#validateを実行したときに発生します。
pre('save')
中にバリデーションが失敗し、エラーを受け取るコールバックが渡されなかった場合、Modelsに関連付けられたdb connectionでerror
イベントが発行され、バリデーションエラーオブジェクトが渡されます。
const conn = mongoose.createConnection(..);
conn.on('error', handleError);
const Product = conn.model('Product', yourSchema);
const dvd = new Product(..);
dvd.save(); // emits error on the `conn` above
これらのエラーをModelレベルで処理したい場合は、以下に示すようにModelにerror
リスナーを追加します。
// registering an error listener on the Model lets us handle errors more locally
Product.on('error', handleError);
SchemaType.prototype.validateAll()
パラメータ
validators
«Array<RegExp|Function|Object>»
このドキュメントパスに複数のバリデーターを追加します。validators内のすべての要素に対してvalidate()
を呼び出します。
SchemaType.prototype.validators
型
- «property»
MongooseがこのSchemaTypeのパスでプロパティを検証するために実行するバリデーター。
例
const schema = new Schema({ name: { type: String, required: true } });
schema.path('name').validators.length; // 1, the `required` validator
SchemaType.set()
パラメータ
option
«String» 設定したいオプションの名前(例:trim、lowercaseなど)value
«Any» 設定したいオプションの値。
戻り値
- «void,void»
このスキーマタイプのデフォルトオプションを設定します。
例
// Make all strings be trimmed by default
mongoose.SchemaTypes.String.set('trim', true);