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 ...
随机推荐
- C2MIF软件使用说明
1.右击---管理员身份运行 2.打开文件txt---搞定!
- Spring Boot教程(十七)属性配置文件详解(2)
通过命令行设置属性值 相信使用过一段时间Spring Boot的用户,一定知道这条命令:java -jar xxx.jar --server.port=8888,通过使用–server.port属性来 ...
- Firefox_64.0 中selenium ide_3.4.4的使用教程(实操)
说明:旧版的selenium IDE有很多功能,在新版中都去除了,很多功能都做不了. 写于:2018.12.31 一.安装selenium IDE 下载和安装这里推荐参考文章:https://blo ...
- Web Api试图加载格式不正确的程序,解决方法
Web Api试图加载格式不正确的程序,错误如下: 问题原因: 出现上述问题的原因是,所加载的程序集中有32位的,也有64位的,IIS 7 程序池 在Windows下.Net FrameWork是64 ...
- [CSP-S模拟测试]:格式化(贪心)
题目传送门(内部题105) 输入格式 每组数据第一行一个正整数$n$,表示硬盘块数,接下来$n$行,每行两个正整数,第一个正整数为硬盘格式化前的容量,第二个正整数为格式化之后的容量. 输出格式 对每组 ...
- [LeetCode]-algorithms-Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...
- 用命令行编译运行java文件的乱码问题
之前在写的时候没有遇到过这个问题,用惯了eclipse之后突然用Notepad++就出现乱码了 我在编写的时候 指定Noepad++的编码是 UTF-8编码,然后进入命令行,编译的时候就出现了乱码 然 ...
- architecture 20190628
https://abp.io/ --ABP v2 官网 https://grpc.io/ --gRPC官网 https://devblogs.microsoft.com/dotnet/introdu ...
- git跟yum一样 linux下的命令使用和思想是类似的
git跟yum一样 linux下的命令使用和思想是类似的
- E: 错误,pkgProblemResolver::Resolve 发生故障,这可能是有软件包被要求保持现状的缘故。 E: 无法更正依赖关系
mentohust:i386 已经是最新的版本了. 您可能需要运行"apt-get -f install"来纠正下列错误: 下列软件包有未满足的依赖关系: mentohust:i ...