SchemaString


SchemaString()

参数
  • key «字符串»
  • options «对象»
继承

字符串模式类型构造函数。


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 实例附加 getter。

示例

// 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 «文档»
返回值
  • «布尔值»

检查给定值是否满足 `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

添加小写 setter

示例

const s = new Schema({ email: { type: String, lowercase: true }})
const M = db.model('M', s);
const m = new M({ email: '[email protected]' });
console.log(m.email) // [email protected]
M.find({ email: '[email protected]' }); // Queries by '[email protected]'

请注意,`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 «正则表达式» 要测试的正则表达式

  • [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

添加一个修剪 setter

字符串值将被 修剪 当设置。

示例

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

添加一个大写 setter

示例

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'