SchemaString
SchemaString()
Параметры:
-
key«String» -
options«Object»
Наследуется от:
Конструктор типа SchemaType для строк.
SchemaString.checkRequired()
Параметры:
-
fn«Function»
Возвращает:
- «Function»
Тип:
- «property»
Переопределите функцию, используемую валидатором обязательности для проверки, проходит ли строка проверку 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«Function»
Возвращает:
- «Function»
Тип:
- «property»
Получение/установка функции, используемой для преобразования произвольных значений в строки.
Пример:
// 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«Function»
Возвращает:
- «this»
Тип:
- «property»
Привязывает геттер ко всем экземплярам строк.
Пример:
// 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«Any» -
doc«Document»
Возвращает:
- «Boolean»
Проверяет, удовлетворяет ли заданное значение валидатору required. Значение считается действительным, если это строка (то есть не null или undefined) и имеет положительную длину. Валидатор required не будет успешно проверять пустые строки.
SchemaString.prototype.enum()
Параметры:
-
[...args]«String|Object» значения перечисления
Возвращает:
- «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: '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]«String» необязательное пользовательское сообщение об ошибке
Возвращает:
- «SchemaType» this
См.:
Устанавливает валидатор regexp.
Любое значение, которое не пройдет 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«Number» максимальная длина строки -
[message]«String» необязательное пользовательское сообщение об ошибке
Возвращает:
- «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«Number» минимальная длина строки -
[message]«String» необязательное пользовательское сообщение об ошибке
Возвращает:
- «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
Тип:
- «property»
Имя этого типа схемы для защиты от минимизаторов, которые изменяют имена функций.
SchemaString.set()
Параметры:
-
option«String» Параметр, для которого вы хотите установить значение -
value«Any» значение для параметра
Возвращает:
- «undefined,void»
Тип:
- «property»
Устанавливает параметр по умолчанию для всех экземпляров строк.
Пример:
// 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'
© 2010 LearnBoost
Licensed under the MIT License.
https://mongoosejs.com/docs/api/schemastring.html