当前位置: 首页 > news >正文

mongoose 之ShemaType

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

    里讲述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}`');




转载于:https://my.oschina.net/antianlu/blog/180157

相关文章:

  • ES6 的 Symbol 超出你想象的强大
  • poj1062
  • 解决iview多表头动态更改列元素发生的错误
  • 比特币淘金热席卷中国专业“挖矿机”受疯抢
  • Python的变量和常量
  • PHP——自定义比较算法
  • 【转】Python 内置函数 locals() 和globals()
  • Openssl加密解密应用
  • 敏捷开发的6个实战经验
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • MySQL通过命令导出导入数据和表
  • python列表中的深浅copy
  • mysql高可用方案之主从架构(master-slave)
  • 中国HBase技术社区第二届MeetUp ——HBase技术解析及应用实践
  • Centos 7.4 安装 Redis 全过程
  • [原]深入对比数据科学工具箱:Python和R 非结构化数据的结构化
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • 【翻译】Mashape是如何管理15000个API和微服务的(三)
  • AngularJS指令开发(1)——参数详解
  • electron原来这么简单----打包你的react、VUE桌面应用程序
  • gcc介绍及安装
  • go语言学习初探(一)
  • Javascripit类型转换比较那点事儿,双等号(==)
  • Python中eval与exec的使用及区别
  • SAP云平台运行环境Cloud Foundry和Neo的区别
  • Spring Boot MyBatis配置多种数据库
  • spring boot下thymeleaf全局静态变量配置
  • 半理解系列--Promise的进化史
  • 对象引论
  • 给自己的博客网站加上酷炫的初音未来音乐游戏?
  • 缓存与缓冲
  • 如何合理的规划jvm性能调优
  • 完善智慧办公建设,小熊U租获京东数千万元A+轮融资 ...
  • ​ssh免密码登录设置及问题总结
  • ​人工智能书单(数学基础篇)
  • ​人工智能之父图灵诞辰纪念日,一起来看最受读者欢迎的AI技术好书
  • !!Dom4j 学习笔记
  • # 20155222 2016-2017-2 《Java程序设计》第5周学习总结
  • (06)Hive——正则表达式
  • (C语言)fread与fwrite详解
  • (Redis使用系列) Springboot 实现Redis消息的订阅与分布 四
  • (vue)el-checkbox 实现展示区分 label 和 value(展示值与选中获取值需不同)
  • (附源码)springboot宠物管理系统 毕业设计 121654
  • (六)c52学习之旅-独立按键
  • (三)mysql_MYSQL(三)
  • (算法)求1到1亿间的质数或素数
  • (一)spring cloud微服务分布式云架构 - Spring Cloud简介
  • (译) 理解 Elixir 中的宏 Macro, 第四部分:深入化
  • (转)MVC3 类型“System.Web.Mvc.ModelClientValidationRule”同时存在
  • (转)用.Net的File控件上传文件的解决方案
  • .describe() python_Python-Win32com-Excel
  • .NET 8.0 中有哪些新的变化?
  • .NET delegate 委托 、 Event 事件,接口回调
  • .NET Micro Framework 4.2 beta 源码探析
  • .NET NPOI导出Excel详解