2019独角兽企业重金招聘Python工程师标准>>>
这里讲述ShemaType在每个属性中的默认配置情况,就连我在没有详细看文档之前,就想:
1.如何使得每个属性比如日期属性,在添加document的时候自动插入日期?
2.比如我有个属性是根据每个几个属性的组合情况而确立该属性的值怎么搞?
3.有一个属性我不想添加到库里,在查询的时候有希望多出这个属性来,咋搞?
反正很多问题吧,不可能写一大堆function来动态添加动态取消,会影响效率和查询性能的等等诸如此类。
譬如我们平时定义情况是:
var schema = new Schema({ name: String, age: Number, children: [child] });
以下是设置Schema属性选项的关键字列表,解释下经常会用到的。
- default 设置默认值
- get 调用处理方法,比如格式化字符串……
- index 设置索引规则
- required 设置验证规则,正则表达式等
- select 设置属性是否总是在查询结果中出现bool
- set 可以修改传来的属性值,和get类似
- sparse 稀疏索引bool,与索引搭配使用
- unique 设置这个属性的值只出现一次,一般对索引设置
- validate 用于对属性的值进行验证,false失败,true通过验证
SchemaType#default(val)
// age属性为其设置数据类型和默认值
var schema = new Schema({ age: { type: Number, default: 10 })
var M = db.model('M', schema)
var m = new M;
console.log(m.age) // 10
现在可以解决我的第一个疑问了
var _UserInfo = new Schema({
nickname: String,
id: Number,
name: String,
gender: Boolean,
birthday: {type:String, get:getBirthday},//getBirthday是一个处理日期方法
age: Number,
regtime: {type:Date , default:Date.now}//当你插入文档,自动就会生成日期
},
{versionKey:false}//这个就是处理掉自动插入文档的__v这个属性
);
当然,在一般情况下有一种方法来设置,也可以有其他方法来设置,js的灵活性没得说,选择性很多,请看如下代码自然名了
// 以下属性aNumber的类型是Number,给他设置一个默认值 4.85162342,只能对单个属性的情况下,说明default是关键字
var schema = new Schema({ aNumber: Number, default: "4.815162342" })
var M = db.model('M', schema)
var m = new M;
console.log(m.aNumber) // 4.815162342
// 对混合类型设置默认值情况:
var schema = new Schema({ mixed: Schema.Types.Mixed });
// schema.path('mixed')获取类型然后使用回调函数设置默认值,为一个空对象
schema.path('mixed').default(function () {
return {};
});
// 如果你不用function回调的话,你设置的默认值会被model的实例共享
var schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default({});
var M = db.model('M', schema);
var m1 = new M;
m1.mixed.added = 1;
console.log(m1.mixed); // { added: 1 }
var m2 = new M;
console.log(m2.mixed); // { added: 1 }
SchemaType#get(fn)
// get属性的作用可以直观的看出把传入的值修改成我们想要的数据格式,最后按照我们制定的格式存入文档
function dob (val) {
if (!val) return val;
return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
}
// defining within the schema
var s = new Schema({ born: { type: Date, get: dob })
// or by retreiving its SchemaType
var s = new Schema({ born: Date })
s.path('born').get(dob)
也可以在查询的时候把属性的值转换为我们想要的输出格式,例如:
function obfuscate (cc) {
return '****-****-****-' + cc.slice(cc.length-4, cc.length);
}
var AccountSchema = new Schema({
creditCardNumber: { type: String, get: obfuscate }
});
var Account = db.model('Account', AccountSchema);
//查询并转换指定格式输出
Account.findById(id, function (err, found) {
console.log(found.creditCardNumber); // '****-****-****-1234'
});
SchemaType#index(options)
设置索引规则var s = new Schema({ name: { type: String, index: true })
var s = new Schema({ loc: { type: [Number], index: 'hashed' })
var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
Schema.path('my.path').index(true);
Schema.path('my.date').index({ expires: 60 });
Schema.path('my.path').index({ unique: true, sparse: true });
SchemaType#required(required, [message])
var s = new Schema({ born: { type: Date, required: true })
// or with custom error message
var s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
// or through the path API
Schema.path('name').required(true);
// with custom error messaging
Schema.path('name').required(true, 'grrr :( ');
SchemaType#select(val)
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#set(fn)
function capitalize (val) {
if ('string' != typeof val) val = '';
return val.charAt(0).toUpperCase() + val.substring(1);
}
// defining within the schema
var s = new Schema({ name: { type: String, set: capitalize }})
// or by retreiving its SchemaType
var s = new Schema({ name: String })
s.path('name').set(capitalize)
SchemaType#sparse(bool)
var s = new Schema({ name: { type: String, sparse: true })
Schema.path('name').index({ sparse: true });
SchemaType#unique(bool)
var s = new Schema({ name: { type: String, unique: true })
Schema.path('name').index({ unique: true });
SchemaType#validate(obj, [errorMsg])
// 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
var custom = [validator, 'Uh oh, {PATH} does not equal "something".']
new Schema({ name: { type: String, validate: custom }});
// adding many validators at a time
var many = [
{ validator: validator, msg: 'uh oh' }
, { validator: anotherValidator, msg: 'failed' }
]
new Schema({ name: { type: String, validate: many }});
// or utilizing SchemaType methods directly:
var schema = new Schema({ name: 'string' });
schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');