mongoose 数据库操作2
mongoose的内置的主要功能解说
除了定义文档结构和你要存储的数据类型外。模式(Schema)还用于下面定义:
· Validators
(异步和同步)
· Defaults -
默认值
· Getters
· Setters
· Indexes -
索引
· Middleware -
中间件
· Methods definition -
方法定义
· Statics definition -
静态定义
· Plugins -
插件
Aside from defining thestructure of your documents and the types of data you're storing, a Schemahandles the definition of:
· Validators (async andsync)
· Defaults
· Getters
· Setters
· Indexes
· Methods definition
· Statics definition
· Plugins
(1)验证器
验证器通过ShcemaType定义
内部使用中间件
默认在使用save操作时自己主动开启(create操作应该是无论用的,这个我们能够试一试)
使用异步操作
验证器能够自己定义
定义验证通过。path(“属性”).validate(function(value){})来定义,我们看看样例:
<pre name="code" class="javascript">
var toySchema =
newSchema({
color: String,
name: String
});
var Toy = mongoose.model('Toy', toySchema);
Toy.schema.path('color').validate(function (value) {
return
/blue|green|white|red|orange|periwinkle/i.test(value);
}, 'Invalid color');
var toy = new
Toy({ color:
'grease'});
toy.save(function (err) {
// err is ourValidationError object
// err.errors.coloris a ValidatorError object
console.log(err.errors.color.message)
// prints'Validator "Invalid color" failed for path color with value `grease`'
console.log(String(err.errors.color))
// prints'Validator "Invalid color" failed for path color with value `grease`'
console.log(err.errors.color.type) // prints "Invalid color"
console.log(err.errors.color.path) // prints "color"
console.log(err.errors.color.value)
// prints"grease"
console.log(err.name)
// prints"ValidationError"
console.log(err.message)
// prints"Validation failed"
});
</pre>
上面的样例非常easy嘛。
假设用不到验证的方法那么。直接create 就能够
Toy.create({xx:xxx},function(err,schema){});
(2)默认值
上样例:
<pre name="code" class="javascript">
var schema =
new Schema({ n: { type: Number, default: })
var M = db.model('M', schema)
var m = new M;
console.log(m.n) // 10
</pre>
在方案(Schema)设置defualt值后,值初始化模型后就能够直接获取这个值,那么我们在插入操作中要怎样去做呢?
<pre name="code" class="javascript">
var db = require('mongoose')
,Schema = db.Schema;
var schema = new Schema({ n: { type: Number, default: 10 }});
db.connect('mongodb://localhost:8888/toy', function (err) {
var Toy = db.model('Toy', schema,"toy");
new Toy({}).save(function(err){
if(err)return console.log(err);
console.log("报错成功");
});
if (err) throw err;
});
这个样例中关键的地方在于new Toy({}) 并没有写n这个对象,那么我们来查一下数据库看一下输出:
<pre name="code" class="javascript">
> db.toy.find()
{ "_id" : ObjectId("5361a5fa62c7cc803624ec0d"),"n" : 10, "__v" : 0 }
</pre>
(3)给模型加入一个静态的方法:
<pre name="code" class="javascript">
// assign afunction to the "statics" object of our animalSchema
animalSchema.statics.findByName =
function (name, cb) {
this.find({ name:
newRegExp(name, 'i') }, cb);
}
var Animal = mongoose.model('Animal',animalSchema);
Animal.findByName('fido',
function (err, animals) {
console.log(animals);
});
</pre>
(4)创建索引:
在mongodb数据库中索引排序1 和 -1 代表正反
<pre name="code" class="javascript">
var animalSchema=
new Schema({
name: String,
type: String,
tags: { type: [String], index:
true } // field level
});
animalSchema.index({ name: , type: - });
// schema level
</pre>
(5)插件就是mongoose提供的一个能够模块化的一个功能,能够把面的一些零散的功能写到一个插件中组合起来,比方set get 方法中间件等写到一个模块中:
<pre name="code" class="javascript">
// lastMod.js
module.exports = exports =function
lastModifiedPlugin (schema, options){
schema.add({ lastMod: Date })
schema.pre('save',
function (next) {
this.lastMod =
new Date
next()
})
if(options && options.index) {
schema.path('lastMod').index(options.index)
}
}
// game-schema.js
var lastMod= require('./lastMod');
varGame = new Schema({ ... });
Game.plugin(lastMod, {index:
true });
// player-schema.js
varlastMod = require('./lastMod');
varPlayer =
new Schema({ ... });
Player.plugin(lastMod);
</pre>
mongoose 数据库操作2的更多相关文章
- mongoose 数据库操作 - 分页
使用mongoose 加入分页方法,临时还没发现什么更好的方法,我使用的方法是,直接在源代码中加入 找到 node_modules/mongoose/lib/model.js打开这个文件.里面加入这段 ...
- mongoose 数据库操作3
Model.find(query, fields, options, callback) Model.find({ 'some.value': 5 }, function (err, docs) { ...
- 转:Mongoose使用操作
一般我们不直接用MongoDB的函数来操作MongoDB数据库 Mongose就是一套操作MongoDB数据库的接口. 连接数据库 // mongoose 链接var mongoose = req ...
- 如何在高并发环境下设计出无锁的数据库操作(Java版本)
一个在线2k的游戏,每秒钟并发都吓死人.传统的hibernate直接插库基本上是不可行的.我就一步步推导出一个无锁的数据库操作. 1. 并发中如何无锁. 一个很简单的思路,把并发转化成为单线程.Jav ...
- 【知识必备】ezSQL,最好用的数据库操作类,让php操作sql更简单~
最近用php做了点小东东,用上了ezSQL,感觉真的很ez,所以拿来跟大家分享一下~ ezSQL是一个非常好用的PHP数据库操作类.著名的开源博客WordPress的数据库操作就使用了ezSQL的My ...
- MySQL 系列(二) 你不知道的数据库操作
第一篇:MySQL 系列(一) 生产标准线上环境安装配置案例及棘手问题解决 第二篇:MySQL 系列(二) 你不知道的数据库操作 本章内容: 查看\创建\使用\删除 数据库 用户管理及授权实战 局域网 ...
- ABP创建数据库操作步骤
1 ABP创建数据库操作步骤 1.1 SimpleTaskSystem.Web项目中的Web.config文件修改数据库配置. <add name="Default" pro ...
- 【第一篇】ASP.NET MVC快速入门之数据库操作(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
- django数据库操作和中间件
数据库配置 django的数据库相关表配置在models.py文件中,数据库的连接相关信息配置在settings.py中 models.py相关相关参数配置 from django.db import ...
随机推荐
- SqlServer 随机生成中文姓名(转)
,) )) -- 姓氏 ,) )) -- 名字 INSERT @fName VALUES ('赵'),('钱'),('孙'),('李'),('周'),('吴'),('郑'),('王'),('冯'),( ...
- HTML5 大文件断点续传完整思路整理
需求: 支持大文件批量上传(20G)和下载,同时需要保证上传期间用户电脑不出现卡死等体验: 内网百兆网络上传速度为12MB/S 服务器内存占用低 支持文件夹上传,文件夹中的文件数量达到1万个以上,且包 ...
- UVa 122 Trees on the level (动态建树 && 层序遍历二叉树)
题意 :输入一棵二叉树,你的任务是按从上到下.从左到右的顺序输出各个结点的值.每个结 点都按照从根结点到它的移动序列给出(L表示左,R表示右).在输入中,每个结点的左 括号和右括号之间没有空格,相邻 ...
- socket模块其他用法
1.socket模块的其他方法 服务端套接字函数 s.bind() 绑定(主机,端口号)到套接字 s.listen() 开始TCP监听 s.accept() 被动接受TCP客户的连接,(阻塞式)等待连 ...
- vue 渲染是出现 Do not use built-in or reserved HTML elements as component id 的警告
情况1.是因为组件命名和引入不一致造成的. 命名组件(nav) export default { name: 'nav', data () { return { } } 引入组件(Navigation ...
- JavaScript json loop item in array
Iterating through/Parsing JSON Object via JavaScript 解答1 Your JSON object is incorrect because it ha ...
- Python 写 ACM 题目的一些技巧
目录 输入输出 input() 输入 split() 用于输入 strip() 输入清理 print() 输入 sort 排序 输入输出 input() 输入 Python3 中 input() 函数 ...
- virt-manager 使用 shh 远程访问配置方法
1.下载安装 Xming+Xshell 或者 Xming+putty,启动Xming服务 Xming下载地址 2.XMing的配置:打开XLaunch,记住Display Number,现在这里是0 ...
- maven 插件的应用
在pom.xml里配置 以测试插件介绍为主 <build> <plugins> <plugin> <groupId>org.apache.maven.p ...
- WINDOWS API 大全(一)
1. API之网络函数 WNetAddConnection 创建同一个网络资源的永久性连接 WNetAddConnection2 创建同一个网络资源的连接 WNetAddConnection3 创建同 ...