-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
schematypes.jade
270 lines (251 loc) · 10.2 KB
/
schematypes.jade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
extends layout
block content
h2 SchemaTypes
p
| SchemaTypes handle definition of path
a(href="./api.html#schematype_SchemaType-default") defaults
|,
a(href="./api.html#schematype_SchemaType-validate") validation
|,
a(href="./api.html#schematype_SchemaType-get") getters
|,
a(href="./api.html#schematype_SchemaType-set") setters
|,
a(href="./api.html#schematype_SchemaType-select") field selection defaults
| for
a(href="./api.html#query-js") queries
| and other general characteristics for
a(href="./api.html#schema-string-js") Strings
| and
a(href="./api.html#schema-number-js") Numbers
|. Check out their respective API documentation for more detail.
p
| Following are all valid
a(href="./api.html#schema_Schema.Types") Schema Types
|.
:markdown
- [String](./api.html#schema-string-js)
- [Number](./api.html#schema-number-js)
- [Date](./api.html#schema-date-js)
- [Buffer](./api.html#schema-buffer-js)
- Boolean
- Mixed
- [Objectid](./api.html#schema-objectid-js)
- Array
h4 Example
:js
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);
h3 SchemaType Options
:markdown
You can declare a schema type using the type directly, or an object with
a `type` property.
:js
var schema1 = new Schema({
test: String // `test` is a path of type String
});
var schema2 = new Schema({
test: { type: String } // `test` is a path of type string
});
:markdown
In addition to the type property, you can specify additional properties
for a path. For example, if you want to lowercase a string before saving:
:js
var schema2 = new Schema({
test: {
type: String,
lowercase: true // Always convert `test` to lowercase
}
});
:markdown
The `lowercase` property only works for strings. There are certain options
which apply for all schema types, and some that apply for specific schema
types.
h5 All Schema Types
:markdown
* `required`: boolean or function, if true adds a [required validator](http://mongoosejs.com/docs/validation.html#built-in-validators) for this property
* `default`: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default.
* `select`: boolean, specifies default [projections](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/) for queries
* `validate: function, adds a [validator function](http://mongoosejs.com/docs/validation.html#built-in-validators) for this property
* `get`: function, defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
* `set`: function, defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
:js
var numberSchema = new Schema({
integerOnly: {
type: Number,
get: v => Math.round(v),
set: v => Math.round(v)
}
});
var Number = mongoose.model('Number', numberSchema);
var doc = new Number();
doc.integerOnly = 2.001;
doc.integerOnly; // 2
h5 Indexes
p
You can also define [MongoDB indexes](https://docs.mongodb.com/manual/indexes/)
using schema type options.
* `index`: boolean, whether to define an on this property.
* `unique`: boolean, whether to define a [unique index](https://docs.mongodb.com/manual/core/index-unique/) on this property.
* `sparse`: boolean, whether to define a [sparse index](https://docs.mongodb.com/manual/core/index-sparse/) on this property.
:js
var schema2 = new Schema({
test: {
type: String,
index: true,
unique: true // Unique index. If you specify `unique: true`
// specifying `index: true` is optional if you do `unique: true`
}
});
h5 String
:markdown
* `lowercase`: boolean, whether to always call `.toLowerCase()` on the value
* `uppercase`: boolean, whether to always call `.toUpperCase()` on the value
* `trim`: boolean, whether to always call `.trim()` on the value
* `match`: RegExp, creates a [validator](http://mongoosejs.com/docs/validation.html) that checks if the value matches the given regular expression
* `enum`: Array, creates a [validator](http://mongoosejs.com/docs/validation.html) that checks if the value is in the given array.
h5 Number
:markdown
* `min`: Number, creates a [validator](http://mongoosejs.com/docs/validation.html) that checks if the value is greater than or equal to the given minimum.
* `max`: Number, creates a [validator](http://mongoosejs.com/docs/validation.html) that checks if the value is less than or equal to the given maximum.
h5 Date
* `min`: Date
* `max`: Date
h3 Usage notes:
h4#Dates Dates
:markdown
[Built-in `Date` methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) are [__not__ hooked into](https://github.com/Automattic/mongoose/issues/1598) 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.
:js
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
})
h4#mixed Mixed
p 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:
:js
var Any = new Schema({ any: {} });
var Any = new Schema({ any: Object });
var Any = new Schema({ any: Schema.Types.Mixed });
p
| 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
code .markModified(path)
| method of the document passing the path to the Mixed type you just changed.
:js
person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved
h4#objectids ObjectIds
p
| To specify a type of ObjectId, use
code Schema.Types.ObjectId
| in your declaration.
:js
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
h4#arrays Arrays
p
| Provide creation of arrays of
a(href="./api.html#schema_Schema.Types") SchemaTypes
| or
a(href="./subdocs.html") Sub-Documents
|.
:js
var ToySchema = new Schema({ name: String });
var ToyBox = new Schema({
toys: [ToySchema],
buffers: [Buffer],
string: [String],
numbers: [Number]
// ... etc
});
p
| Note: specifying an empty array is equivalent to
code Mixed
|. The following all create arrays of
code Mixed
|:
:js
var Empty1 = new Schema({ any: [] });
var Empty2 = new Schema({ any: Array });
var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
var Empty4 = new Schema({ any: [{}] });
h3#customtypes Creating Custom Types
p
| Mongoose can also be extended with custom SchemaTypes. Search the
a(href="http://plugins.mongoosejs.com") plugins
| site for compatible types like
a(href="https://github.com/aheckmann/mongoose-long") mongoose-long
| ,
a(href="https://github.com/vkarpov15/mongoose-int32") mongoose-int32
| and
a(href="https://github.com/aheckmann/mongoose-function") other
|
a(href="https://github.com/OpenifyIt/mongoose-types") types
|.
| To create your own custom schema take a look at
a(href="/docs/customschematypes.html") Creating a Basic Custom Schema Type
|.
h3#path The `schema.path()` Function
:markdown
The `schema.path()` function returns the instantiated schema type for a
given path.
:js
var sampleSchema = new Schema({ name: { type: String, required: true } });
console.log(sampleSchema.path('name'));
// Output looks like:
/**
* SchemaString {
* enumValues: [],
* regExp: null,
* path: 'name',
* instance: 'String',
* validators: ...
*/
:markdown
You can use this function to inspect the schema type for a given path,
including what validators it has and what the type is.
h3#next Next Up
:markdown
Now that we've covered `SchemaTypes`, let's take a look at [Models](/docs/models.html).