SchemaString


SchemaString()

パラメーター
  • key «文字列»
  • options «オブジェクト»
継承

String SchemaType コンストラクタ。


SchemaString.checkRequired()

パラメーター
  • fn «関数»
戻り値
  • «関数»
  • «プロパティ»

必須バリデータが文字列がrequiredチェックに合格するかどうかを確認するために使用する関数をオーバーライドします。

// Allow empty strings to pass `required` check
mongoose.Schema.Types.String.checkRequired(v => v != null);

const M = mongoose.model({ str: { type: String, required: true } });
new M({ str: '' }).validateSync(); // `null`, validation passes!

SchemaString.get()

パラメーター
  • caster «関数»
戻り値
  • «関数»
  • «プロパティ»

任意の値を文字列にキャストするために使用される関数を取得/設定します。

// Throw an error if you pass in an object. Normally, Mongoose allows
// objects with custom `toString()` functions.
const original = mongoose.Schema.Types.String.cast();
mongoose.Schema.Types.String.cast(v => {
  assert.ok(v == null || typeof v !== 'object');
  return original(v);
});

// Or disable casting entirely
mongoose.Schema.Types.String.cast(false);

SchemaString.get()

パラメーター
  • getter «関数»
戻り値
  • «this»
  • «プロパティ»

すべてのStringインスタンスにゲッターをアタッチします。

// Make all numbers round down
mongoose.Schema.String.get(v => v.toLowerCase());

const Model = mongoose.model('Test', new Schema({ test: String }));
new Model({ test: 'FOO' }).test; // 'foo'

SchemaString.prototype.checkRequired()

パラメーター
  • value «任意»
  • doc «Document»
戻り値
  • «ブール値»

指定された値がrequiredバリデータに適合するかどうかを確認します。値は、文字列(つまり、nullまたはundefinedではない)であり、長さが正の場合、有効と見なされます。requiredバリデータは、空文字列に対しては**失敗**します。


SchemaString.prototype.enum()

パラメーター
  • [...args] «文字列|オブジェクト» 列挙値

戻り値
  • «SchemaType» this
参照

列挙バリデータを追加します。

const states = ['opening', 'open', 'closing', 'closed']
const s = new Schema({ state: { type: String, enum: states }})
const M = db.model('M', s)
const m = new M({ state: 'invalid' })
m.save(function (err) {
  console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
  m.state = 'open'
  m.save(callback) // success
})

// or with custom error messages
const enum = {
  values: ['opening', 'open', 'closing', 'closed'],
  message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
}
const s = new Schema({ state: { type: String, enum: enum })
const M = db.model('M', s)
const m = new M({ state: 'invalid' })
m.save(function (err) {
  console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
  m.state = 'open'
  m.save(callback) // success
})

SchemaString.prototype.lowercase()

戻り値
  • «SchemaType» this

小文字のセッターを追加します。

const s = new Schema({ email: { type: String, lowercase: true }})
const M = db.model('M', s);
const m = new M({ email: 'SomeEmail@example.COM' });
console.log(m.email) // someemail@example.com
M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com'

lowercaseは、正規表現クエリには**影響しません**。

// Still queries for documents whose `email` matches the regular
// expression /SomeEmail/. Mongoose does **not** convert the RegExp
// to lowercase.
M.find({ email: /SomeEmail/ });

SchemaString.prototype.match()

パラメーター
  • regExp «RegExp» テストする正規表現

  • [message] «文字列» オプションのカスタムエラーメッセージ

戻り値
  • «SchemaType» this
参照

正規表現バリデータを設定します。

regExp.test(val)に合格しない値は、バリデーションに失敗します。

const s = new Schema({ name: { type: String, match: /^a/ }})
const M = db.model('M', s)
const m = new M({ name: 'I am invalid' })
m.validate(function (err) {
  console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
  m.name = 'apples'
  m.validate(function (err) {
    assert.ok(err) // success
  })
})

// using a custom error message
const match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
const s = new Schema({ file: { type: String, match: match }})
const M = db.model('M', s);
const m = new M({ file: 'invalid' });
m.validate(function (err) {
  console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
})

空文字列、undefined、およびnull値は、常に一致バリデータに合格します。これらの値が必要な場合は、requiredバリデータも有効にしてください。

const s = new Schema({ name: { type: String, match: /^a/, required: true }})

SchemaString.prototype.maxlength()

パラメーター
  • value «数値» 最大文字列長

  • [message] «文字列» オプションのカスタムエラーメッセージ

戻り値
  • «SchemaType» this
参照

最大長バリデータを設定します。

const schema = new Schema({ postalCode: { type: String, maxlength: 9 })
const Address = db.model('Address', schema)
const address = new Address({ postalCode: '9512512345' })
address.save(function (err) {
  console.error(err) // validator error
  address.postalCode = '95125';
  address.save() // success
})

// custom error messages
// We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length
const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
const schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
const Address = mongoose.model('Address', schema);
const address = new Address({ postalCode: '9512512345' });
address.validate(function (err) {
  console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9).
})

SchemaString.prototype.minlength()

パラメーター
  • value «数値» 最小文字列長

  • [message] «文字列» オプションのカスタムエラーメッセージ

戻り値
  • «SchemaType» this
参照

最小長バリデータを設定します。

const schema = new Schema({ postalCode: { type: String, minlength: 5 })
const Address = db.model('Address', schema)
const address = new Address({ postalCode: '9512' })
address.save(function (err) {
  console.error(err) // validator error
  address.postalCode = '95125';
  address.save() // success
})

// custom error messages
// We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length
const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
const schema = new Schema({ postalCode: { type: String, minlength: minlength })
const Address = mongoose.model('Address', schema);
const address = new Address({ postalCode: '9512' });
address.validate(function (err) {
  console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
})

SchemaString.prototype.trim()

戻り値
  • «SchemaType» this

トリムセッターを追加します。

文字列値は、設定時にトリムされます。

const s = new Schema({ name: { type: String, trim: true }});
const M = db.model('M', s);
const string = ' some name ';
console.log(string.length); // 11
const m = new M({ name: string });
console.log(m.name.length); // 9

// Equivalent to `findOne({ name: string.trim() })`
M.findOne({ name: string });

trimは、正規表現クエリには**影響しません**。

// Mongoose does **not** trim whitespace from the RegExp.
M.find({ name: / some name / });

SchemaString.prototype.uppercase()

戻り値
  • «SchemaType» this

大文字のセッターを追加します。

const s = new Schema({ caps: { type: String, uppercase: true }})
const M = db.model('M', s);
const m = new M({ caps: 'an example' });
console.log(m.caps) // AN EXAMPLE
M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE'

uppercaseは、正規表現クエリには**影響しません**。

// Mongoose does **not** convert the RegExp to uppercase.
M.find({ email: /an example/ });

SchemaString.schemaName

  • «プロパティ»

関数名を変更するミニファイアから保護するための、このスキーマタイプの名前です。


SchemaString.set()

パラメーター
  • option «文字列» 値を設定するオプション

  • value «任意» オプションの値

戻り値
  • «undefined,void»
  • «プロパティ»

すべてのStringインスタンスのデフォルトオプションを設定します。

// Make all strings have option `trim` equal to true.
mongoose.Schema.String.set('trim', true);

const User = mongoose.model('User', new Schema({ name: String }));
new User({ name: '   John Doe   ' }).name; // 'John Doe'