SchemaString
SchemaString()
SchemaString.checkRequired()
SchemaString.get()
SchemaString.get()
SchemaString.prototype.checkRequired()
SchemaString.prototype.enum()
SchemaString.prototype.lowercase()
SchemaString.prototype.match()
SchemaString.prototype.maxlength()
SchemaString.prototype.minlength()
SchemaString.prototype.trim()
SchemaString.prototype.uppercase()
SchemaString.schemaName
SchemaString.set()
SchemaString()
參數
key
«字串»options
«物件»
繼承
字串綱要類型建構函式。
SchemaString.checkRequired()
參數
fn
«函式»
回傳
- «函式»
類型
- «屬性»
覆寫 required 驗證器用來檢查字串是否通過 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»
類型
- «屬性»
為所有字串實例附加 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: '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
«正規表示式» 要測試的正規表示式[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
值總是通過 match 驗證器。 如果您需要這些值,請同時啟用 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
新增一個 trim 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»
類型
- «屬性»
為所有字串實例設定預設選項。
範例
// 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'