SchemaTypes 数据类型

SchemaTypes handle definition of path defaults, validation, getters, setters, field selection defaults for queries and other general characteristics for Strings and Numbers. Check out their respective API documentation for more detail.

数据类型用于定义默认路径, 验证方式, 获取/设置方法,用于数据库查询的默认字段,以及其他针对字符串与数字的特性。关于详细信息请查阅相关API文档。

译注:默认路径即某个域相对于文档而言的路径,如{a: 1}这个文档中,若指定路径为’a’,即可访问到1这个数据。

Following are all valid Schema Types.
接下来是Mongoose中所有可用的数据类型。

  • String
    字符串
  • Number
    数字
  • Date
    日期
  • Buffer
    缓冲区
  • Boolean
    布尔值
  • Mixed
    混合
  • Objectid
    对象ID
  • Array
    数组

Example
举个栗子!

var schema = new Schema({
name: String,
binary: Buffer,
living: Boolean,
updated: { type: Date, default: Date.now },
age: { type: Number, min: 18, max: 65 },
mixed: Schema.Types.Mixed,
_someId: Schema.Types.ObjectId,
array: [],
ofString: [String],
ofNumber: [Number],
ofDates: [Date],
ofBuffer: [Buffer],
ofBoolean: [Boolean],
ofMixed: [Schema.Types.Mixed],
ofObjectId: [Schema.Types.ObjectId],
nested: {
stuff: { type: String, lowercase: true, trim: true }
}
}) // example use var Thing = mongoose.model('Thing', schema); var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = new Buffer(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.save(callback);
 

Usage notes 用法要点

Dates 日期型

Built-in Date methods are not hooked into the mongoose change tracking logic which in English means that if you use a Date in your document and modify it with a method like setMonth(), mongoose will be unaware of this change and doc.save() will not persist this modification. If you must modify Date types using built-in methods, tell mongoose about the change with doc.markModified(‘pathToYourDate’) before saving.

Mongoose不跟踪JS内建的日期方法对数据造成的改变。这意味着如果你在文档中使用Date 类型并用setMonth之类的方法去修改它,Mongoose不会意识到它的改变,调用doc.save方法保存时不会保留这个修改。如果你一定要用JS内建的方法修改Date类型的数据,在保存之前用doc.markModified 方法告诉Mongoose这个改变。

var Assignment = mongoose.model('Assignment', { dueDate: Date });
Assignment.findOne(function (err, doc) {
doc.dueDate.setMonth(3);
doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE doc.markModified('dueDate');
doc.save(callback); // works
})

Mixed 混合型

An “anything goes” SchemaType, its flexibility comes at a trade-off of it being harder to maintain. Mixed is available either through Schema.Types.Mixed or by passing an empty object literal. The following are equivalent:

混合型是一种“存啥都行”的数据类型,它的灵活性来自于对可维护性的妥协。Mixed类型用Schema.Types.Mixed 或者一个字面上的空对象{}来定义。下面的定义是等价的:

var Any = new Schema({ any: {} });
var Any = new Schema({ any: Schema.Types.Mixed });

Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To “tell” Mongoose that the value of a Mixed type has changed, call the .markModified(path) method of the document passing the path to the Mixed type you just changed.

因为它是一种 无拘无束,无法无天 无固定模式的类型,所以你可以想怎么改就怎么改,但是Mongoose 没有能力去自动检测和保存这些改动。请通过调用doc.markModified 方法来告诉Mongoose某个混合类型的值被改变了。

person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved

ObjectIds 对象ID型

To specify a type of ObjectId, use Schema.Types.ObjectId in your declaration.
Schema.Types.ObjectId 来声明一个对象ID类型。

译注:对象ID同MongoDB内置的_id 的类型。由24位Hash字符串。

var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var Car = new Schema({ driver: ObjectId });
// or just Schema.ObjectId for backwards compatibility with v2

Arrays 数组型

Provide creation of arrays of SchemaTypes or Sub-Documents.
提供创造各种数据类型或子文档的数组的方法。

var ToySchema = new Schema({ name: String });
var ToyBox = new Schema({
toys: [ToySchema],
buffers: [Buffer],
string: [String],
numbers: [Number]
// ... etc
});

Note: specifying an empty array is equivalent to Mixed. The following all create arrays of Mixed:
注意:用一个空数组来定义等价于创建一个混合型的数组。下面都是创建混合型数组的例子:

var Empty1 = new Schema({ any: [] });
var Empty2 = new Schema({ any: Array });
var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
var Empty4 = new Schema({ any: [{}] });

Creating Custom Types 创建自定义类型

Mongoose can also be extended with custom SchemaTypes. Search the plugins site for compatible types like mongoose-long, mongoose-int32 and other types. To create your own custom schema take a look at Creating a Basic Custom Schema Type.
Mongoose也支持使用自定义的数据类型来拓展功能。从Mongoose插件站搜索合适的类型,比如mongoose-long,mongoose-int32或者其他类型。 想要自己创建类型的话请参考创建一个基础的自定义数据类型。


Mongoose之 SchemaTypes 数据类型的更多相关文章

  1. Mongoose 基本用法

    1. SchemaTypes数据类型 数据类型 描述 String 字符串 Number 数字 Date 日期 Boolean 布尔值 Mixed 混合 Objectid 对象ID Array 数组 ...

  2. Mongodb 数据类型及Mongoose常用CURD

    前言 看完了Node.js实战,其中在数据存储部分提到了Redis.Mongodb,我自己也根据书中的介绍写了几个简单的demo,在demo的过程首先遇到的问题就是数据类型和常见的CURD写法. mo ...

  3. Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose

    参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...

  4. Mongodb 与 Mongoose 的使用

    目标 无明确目标 知识点 了解 mongodb (http://www.mongodb.org/ ) 学习 mongoose 的使用 (http://mongoosejs.com/ ) 课程内容 mo ...

  5. Mongo基础使用,以及在Express项目中使用Mongoose

    MongoDB的基本使用 MongoDB特点: 使用BSON存储数据 支持相对丰富的查询操作(相对其他nosql数据库) 支持索引 副本集(支持多个实例/多个服务器运行同个数据库) 分片(数据库水平扩 ...

  6. Nodejs之MEAN栈开发(三)---- 使用Mongoose创建模型及API

    继续开扒我们的MEAN栈开发之路,前面两节我们学习了Express.Jade引擎并创建了几个静态页面,最后通过Heroku部署了应用. Nodejs之MEAN栈开发(一)---- 路由与控制器 Nod ...

  7. Mongoose学习参考文档——基础篇

    Mongoose学习参考文档 前言:本学习参考文档仅供参考,如有问题,师请雅正 一.快速通道 1.1 名词解释 Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力 Model ...

  8. Mongoose学习参考文档

    一.快速通道 1.1 名词解释 Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力 Model : 由Schema发布生成的模型,具有抽象属性和行为的数据库操作对 Entit ...

  9. Mongoose 是什么?

    Mongoose 参考手册 标签(空格分隔): MongoDB 一般我们不直接用MongoDB的函数来操作MongoDB数据库 Mongose就是一套操作MongoDB数据库的接口. Schema 一 ...

随机推荐

  1. bzoj1087 [SCOI2005][状压DP] 互不侵犯King (状压)

    在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案.国王能攻击到它上下左右,以及左上左下右上右下八个方向上附近的各一个格子,共8个格子. Input 只有一行,包含两个数N,K ( 1 ...

  2. Spring REST 与 Zuul 代理

    http://www.baeldung.com/spring-rest-with-zuul-proxy 作者: Eugen Paraschiv 译者: http://oopsguy.com 1.概述 ...

  3. java数据库编程之高级查询

    第三章:高级查询(-) 3.1:修改表 3.1.1:修改表 语法: Alter table <旧表名> rename [ TO] <新表名>; 例子:Alter table ` ...

  4. django使用xlwt导出excel文件

    这里只是mark一下导出的方法,并没有做什么REST处理和异常处理. 维护统一的style样式,可以使导出的数据更加美观. def export_excel(request): # 设置HttpRes ...

  5. marked插件在线实时解析markdown的web小工具

    访问地址: https://mdrush.herokuapp.com/ github项目: https://github.com/qcer/MDRush 实现简介: 1.动态数据绑定 借助Vuejs, ...

  6. Mysql数据库导出数据字典文档Word或者HTML的3个工具

    最近需要将Mysql的数据库导出一份Word的文档出来,本文记录调研后几个可用的工具和方法: 阿里云DMS工具导出 适用于存储在阿里云RDS服务中的Mysql数据库 导出格式支持:Word.Excel ...

  7. WPF DelegateCommand 出现Specified cast is not valid

    使用 DelegateCommand 出现 Specified cast is not valid 最近写快捷键需要 DelegateCommand ,于是用了 DelegateCommand< ...

  8. C#命令行解析工具

    我将告诉大家两个方法去获取C#输入的命令行参数. 第一个方法: 林选臣大神写的,他的方法很简单. 首先复制两个类到项目 public class CommandLineArgumentParser { ...

  9. win10 uwp 获取按钮鼠标左键按下

    我们可以使用PointerPressed获得鼠标右键按下,但是我们如何获得左键? 其实UWP已经没有MouseLeftButtonDown,于是我们可以使用一个简单方法去获取鼠标左键按下. 我们在xa ...

  10. Python学习笔记(五)

    Python学习笔记(五): 文件操作 另一种文件打开方式-with 作业-三级菜单高大上版 1. 知识点 能调用方法的一定是对象 涉及文件的三个过程:打开-操作-关闭 python3中一个汉字就是一 ...