Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 344 lines (233 sloc) 11.844 kb
55b825bd » guille
2011-01-25 Updated README and example
1 ## What's Mongoose?
2
2d50d64f » aheckmann
2012-02-09 updated readme
3 Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
55b825bd » guille
2011-01-25 Updated README and example
4
5 Defining a model is as easy as:
6
39ad6b20 » afanasy
2012-03-09 Update README.md
7 var Comment = new Schema({
2d50d64f » aheckmann
2012-02-09 updated readme
8 title : String
9 , body : String
10 , date : Date
11 });
12
13 var BlogPost = new Schema({
14 author : ObjectId
15 , title : String
16 , body : String
17 , buf : Buffer
18 , date : Date
39ad6b20 » afanasy
2012-03-09 Update README.md
19 , comments : [Comment]
2d50d64f » aheckmann
2012-02-09 updated readme
20 , meta : {
21 votes : Number
22 , favs : Number
23 }
24 });
25
26 var Post = mongoose.model('BlogPost', BlogPost);
55b825bd » guille
2011-01-25 Updated README and example
27
c6593956 » aheckmann
2012-08-24 docs; fix links
28 ## Documentation
29
30 [mongoosejs.com](http://mongoosejs.com/)
31
f7b06489 » guille
2011-02-01 Added installation section
32 ## Installation
33
2c293e0b » aheckmann
2011-08-23 release 2.0.0
34 The recommended way is through the excellent [NPM](http://www.npmjs.org/):
f7b06489 » guille
2011-02-01 Added installation section
35
2d50d64f » aheckmann
2012-02-09 updated readme
36 $ npm install mongoose
f7b06489 » guille
2011-02-01 Added installation section
37
38 Otherwise, you can check it in your repository and then expose it:
39
2d50d64f » aheckmann
2012-02-09 updated readme
40 $ git clone git://github.com/LearnBoost/mongoose.git node_modules/mongoose/
41
a544842e » tricknotes
2011-12-20 fixed README
42 And install dependency modules written on `package.json`.
f7b06489 » guille
2011-02-01 Added installation section
43
69ce567a » Zearin
2011-06-17 Added syntax highlighting.
44 Then you can `require` it:
f7b06489 » guille
2011-02-01 Added installation section
45
2d50d64f » aheckmann
2012-02-09 updated readme
46 require('mongoose')
f7b06489 » guille
2011-02-01 Added installation section
47
bf7f1df1 » guille
2011-01-25 Reformated
48 ## Connecting to MongoDB
55b825bd » guille
2011-01-25 Updated README and example
49
2d50d64f » aheckmann
2012-02-09 updated readme
50 First, we need to define a connection. If your app uses only one database, you should use `mongose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
55b825bd » guille
2011-01-25 Updated README and example
51
2d50d64f » aheckmann
2012-02-09 updated readme
52 Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
55b825bd » guille
2011-01-25 Updated README and example
53
2d50d64f » aheckmann
2012-02-09 updated readme
54 var mongoose = require('mongoose');
55b825bd » guille
2011-01-25 Updated README and example
55
2d50d64f » aheckmann
2012-02-09 updated readme
56 mongoose.connect('mongodb://localhost/my_database');
55b825bd » guille
2011-01-25 Updated README and example
57
2d50d64f » aheckmann
2012-02-09 updated readme
58 Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
55b825bd » guille
2011-01-25 Updated README and example
59
2d50d64f » aheckmann
2012-02-09 updated readme
60 **Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
55b825bd » guille
2011-01-25 Updated README and example
61
bf7f1df1 » guille
2011-01-25 Reformated
62 ## Defining a Model
55b825bd » guille
2011-01-25 Updated README and example
63
64 Models are defined through the `Schema` interface.
65
2d50d64f » aheckmann
2012-02-09 updated readme
66 var Schema = mongoose.Schema
67 , ObjectId = Schema.ObjectId;
55b825bd » guille
2011-01-25 Updated README and example
68
2d50d64f » aheckmann
2012-02-09 updated readme
69 var BlogPost = new Schema({
70 author : ObjectId
71 , title : String
72 , body : String
73 , date : Date
74 });
55b825bd » guille
2011-01-25 Updated README and example
75
2d50d64f » aheckmann
2012-02-09 updated readme
76 Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
55b825bd » guille
2011-01-25 Updated README and example
77
2c293e0b » aheckmann
2011-08-23 release 2.0.0
78 * [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
c6593956 » aheckmann
2012-08-24 docs; fix links
79 * [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
80 * [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
81 * [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
82 * [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
2c293e0b » aheckmann
2011-08-23 release 2.0.0
83 * [Middleware](http://mongoosejs.com/docs/middleware.html)
c6593956 » aheckmann
2012-08-24 docs; fix links
84 * [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
85 * [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
2c293e0b » aheckmann
2011-08-23 release 2.0.0
86 * [Plugins](http://mongoosejs.com/docs/plugins.html)
c6593956 » aheckmann
2012-08-24 docs; fix links
87 * [psuedo-JOINs](http://mongoosejs.com/docs/populate.html)
55b825bd » guille
2011-01-25 Updated README and example
88
b4ea66ac » guille
2011-01-25 Updated readme and example
89 The following example shows some of these features:
90
2d50d64f » aheckmann
2012-02-09 updated readme
91 var Comment = new Schema({
92 name : { type: String, default: 'hahaha' }
93 , age : { type: Number, min: 18, index: true }
94 , bio : { type: String, match: /[a-z]/ }
95 , date : { type: Date, default: Date.now }
96 , buff : Buffer
97 });
98
99 // a setter
100 Comment.path('name').set(function (v) {
101 return capitalize(v);
102 });
103
104 // middleware
105 Comment.pre('save', function (next) {
106 notify(this.get('email'));
107 next();
108 });
109
110 Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
55b825bd » guille
2011-01-25 Updated README and example
111
bf7f1df1 » guille
2011-01-25 Reformated
112 ## Accessing a Model
55b825bd » guille
2011-01-25 Updated README and example
113
2d50d64f » aheckmann
2012-02-09 updated readme
114 Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
55b825bd » guille
2011-01-25 Updated README and example
115
2d50d64f » aheckmann
2012-02-09 updated readme
116 var myModel = mongoose.model('ModelName');
55b825bd » guille
2011-01-25 Updated README and example
117
c8f4d403 » aheckmann
2011-07-29 fix indentation
118 Or just do it all at once
119
2d50d64f » aheckmann
2012-02-09 updated readme
120 var MyModel = mongoose.model('ModelName', mySchema);
c8f4d403 » aheckmann
2011-07-29 fix indentation
121
121df320 » aheckmann
2012-02-09 docs
122 We can then instantiate it, and save it:
55b825bd » guille
2011-01-25 Updated README and example
123
2d50d64f » aheckmann
2012-02-09 updated readme
124 var instance = new MyModel();
125 instance.my.key = 'hello';
126 instance.save(function (err) {
127 //
128 });
55b825bd » guille
2011-01-25 Updated README and example
129
130 Or we can find documents from the same collection
131
2d50d64f » aheckmann
2012-02-09 updated readme
132 MyModel.find({}, function (err, docs) {
133 // docs.forEach
134 });
55b825bd » guille
2011-01-25 Updated README and example
135
c6593956 » aheckmann
2012-08-24 docs; fix links
136 You can also `findOne`, `findById`, `update`, etc. For more details check out [this link](http://mongoosejs.com/docs/queries.html).
55b825bd » guille
2011-01-25 Updated README and example
137
2d50d64f » aheckmann
2012-02-09 updated readme
138 **Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
121df320 » aheckmann
2012-02-09 docs
139
2d50d64f » aheckmann
2012-02-09 updated readme
140 var conn = mongoose.createConnection('your connection string');
141 var MyModel = conn.model('ModelName', schema);
142 var m = new MyModel;
143 m.save() // works
121df320 » aheckmann
2012-02-09 docs
144
2d50d64f » aheckmann
2012-02-09 updated readme
145 vs
121df320 » aheckmann
2012-02-09 docs
146
2d50d64f » aheckmann
2012-02-09 updated readme
147 var conn = mongoose.createConnection('your connection string');
148 var MyModel = mongoose.model('ModelName', schema);
149 var m = new MyModel;
150 m.save() // does not work b/c the default connection object was never connected
121df320 » aheckmann
2012-02-09 docs
151
bf7f1df1 » guille
2011-01-25 Reformated
152 ## Embedded Documents
55b825bd » guille
2011-01-25 Updated README and example
153
154 In the first example snippet, we defined a key in the Schema that looks like:
155
2d50d64f » aheckmann
2012-02-09 updated readme
156 comments: [Comments]
55b825bd » guille
2011-01-25 Updated README and example
157
2d50d64f » aheckmann
2012-02-09 updated readme
158 Where `Comments` is a `Schema` we created. This means that creating embedded documents is as simple as:
55b825bd » guille
2011-01-25 Updated README and example
159
2d50d64f » aheckmann
2012-02-09 updated readme
160 // retrieve my model
161 var BlogPost = mongoose.model('BlogPost');
55b825bd » guille
2011-01-25 Updated README and example
162
2d50d64f » aheckmann
2012-02-09 updated readme
163 // create a blog post
164 var post = new BlogPost();
55b825bd » guille
2011-01-25 Updated README and example
165
2d50d64f » aheckmann
2012-02-09 updated readme
166 // create a comment
167 post.comments.push({ title: 'My comment' });
55b825bd » guille
2011-01-25 Updated README and example
168
2d50d64f » aheckmann
2012-02-09 updated readme
169 post.save(function (err) {
170 if (!err) console.log('Success!');
171 });
55b825bd » guille
2011-01-25 Updated README and example
172
173 The same goes for removing them:
174
2d50d64f » aheckmann
2012-02-09 updated readme
175 BlogPost.findById(myId, function (err, post) {
176 if (!err) {
177 post.comments[0].remove();
178 post.save(function (err) {
179 // do something
180 });
181 }
55b825bd » guille
2011-01-25 Updated README and example
182 });
183
2d50d64f » aheckmann
2012-02-09 updated readme
184 Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap!
55b825bd » guille
2011-01-25 Updated README and example
185
2d50d64f » aheckmann
2012-02-09 updated readme
186 Mongoose interacts with your embedded documents in arrays _atomically_, out of the box.
55b825bd » guille
2011-01-25 Updated README and example
187
bf7f1df1 » guille
2011-01-25 Reformated
188 ## Middleware
55b825bd » guille
2011-01-25 Updated README and example
189
2d50d64f » aheckmann
2012-02-09 updated readme
190 Middleware is one of the most exciting features about Mongoose. Middleware takes away all the pain of nested callbacks.
55b825bd » guille
2011-01-25 Updated README and example
191
2d50d64f » aheckmann
2012-02-09 updated readme
192 Middleware are defined at the Schema level and are applied for the methods `init` (when a document is initialized with data from MongoDB), `save` (when a document or embedded document is saved).
55b825bd » guille
2011-01-25 Updated README and example
193
c21433ed » bnoguchi
2011-05-22 Updated README to reflect changes to the middleware api.
194 There's two types of middleware:
55b825bd » guille
2011-01-25 Updated README and example
195
196 - Serial
197 Serial middleware are defined like:
198
2d50d64f » aheckmann
2012-02-09 updated readme
199 .pre(method, function (next, methodArg1, methodArg2, ...) {
200 // ...
201 })
55b825bd » guille
2011-01-25 Updated README and example
202
203 They're executed one after the other, when each middleware calls `next`.
204
2d50d64f » aheckmann
2012-02-09 updated readme
205 You can also intercept the `method`'s incoming arguments via your middleware -- notice `methodArg1`, `methodArg2`, etc in the `pre` definition above. See section "Intercepting and mutating method arguments" below.
206
c21433ed » bnoguchi
2011-05-22 Updated README to reflect changes to the middleware api.
207
55b825bd » guille
2011-01-25 Updated README and example
208 - Parallel
2d50d64f » aheckmann
2012-02-09 updated readme
209 Parallel middleware offer more fine-grained flow control, and are defined like:
210
211 .pre(method, true, function (next, done, methodArg1, methodArg2) {
212 // ...
213 })
214
215 Parallel middleware can `next()` immediately, but the final argument will be called when all the parallel middleware have called `done()`.
55b825bd » guille
2011-01-25 Updated README and example
216
bf7f1df1 » guille
2011-01-25 Reformated
217 ### Error handling
55b825bd » guille
2011-01-25 Updated README and example
218
2d50d64f » aheckmann
2012-02-09 updated readme
219 If any middleware calls `next` or `done` with an `Error` instance, the flow is interrupted, and the error is passed to the function passed as an argument.
55b825bd » guille
2011-01-25 Updated README and example
220
221 For example:
222
2d50d64f » aheckmann
2012-02-09 updated readme
223 schema.pre('save', function (next) {
224 // something goes wrong
225 next(new Error('something went wrong'));
226 });
55b825bd » guille
2011-01-25 Updated README and example
227
2d50d64f » aheckmann
2012-02-09 updated readme
228 // later...
55b825bd » guille
2011-01-25 Updated README and example
229
2d50d64f » aheckmann
2012-02-09 updated readme
230 myModel.save(function (err) {
231 // err can come from a middleware
232 });
55b825bd » guille
2011-01-25 Updated README and example
233
c21433ed » bnoguchi
2011-05-22 Updated README to reflect changes to the middleware api.
234 ### Intercepting and mutating method arguments
235
236 You can intercept method arguments via middleware.
237
2d50d64f » aheckmann
2012-02-09 updated readme
238 For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:
239
240 schema.pre('set', function (next, path, val, typel) {
241 // `this` is the current Document
242 this.emit('set', path, val);
243
244 // Pass control to the next pre
245 next();
246 });
247
248 Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`:
249
250 .pre(method, function firstPre (next, methodArg1, methodArg2) {
251 // Mutate methodArg1
252 next("altered-" + methodArg1.toString(), methodArg2);
253 })
254
255 // pre declaration is chainable
256 .pre(method, function secondPre (next, methodArg1, methodArg2) {
257 console.log(methodArg1);
258 // => 'altered-originalValOfMethodArg1'
259
260 console.log(methodArg2);
261 // => 'originalValOfMethodArg2'
262
263 // Passing no arguments to `next` automatically passes along the current argument values
264 // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
265 // and also equivalent to, with the example method arg
266 // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
267 next();
268 })
c21433ed » bnoguchi
2011-05-22 Updated README to reflect changes to the middleware api.
269
c974aa2d » aheckmann
2011-08-05 update README with schema 'type' use
270 ### Schema gotcha
271
2d50d64f » aheckmann
2012-02-09 updated readme
272 `type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation:
273
274 new Schema({
275 broken: { type: Boolean }
276 , asset : {
277 name: String
278 , type: String // uh oh, it broke. asset will be interpreted as String
279 }
280 });
281
282 new Schema({
283 works: { type: Boolean }
284 , asset : {
285 name: String
286 , type: { type: String } // works. asset is an object with a type property
287 }
288 });
c974aa2d » aheckmann
2011-08-05 update README with schema 'type' use
289
55b825bd » guille
2011-01-25 Updated README and example
290 ## API docs
291
2d50d64f » aheckmann
2012-02-09 updated readme
292 You can find the [Dox](http://github.com/visionmedia/dox) generated API docs [here](http://mongoosejs.com/docs/api.html).
55b825bd » guille
2011-01-25 Updated README and example
293
734b3215 » guille
2011-02-01 Added section on support/help
294 ## Getting support
295
42ed1e19 » aheckmann
2012-08-07 docs
296 - Google Groups [mailing list](http://groups.google.com/group/mongoose-orm)
297 - (irc) #mongoosejs on freenode
298 - reporting [issues](https://github.com/learnboost/mongoose/issues/)
299 - [10gen](http://www.mongodb.org/display/DOCS/Technical+Support)
36fa0c7e » aheckmann
2011-08-17 add #mongoosejs to README
300
943cc863 » aheckmann
2011-08-01 add note about native driver to README
301 ## Driver access
302
c6593956 » aheckmann
2012-08-24 docs; fix links
303 The driver being used defaults to [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) and is directly accessible through `YourModel.collection`. **Note**: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc.
943cc863 » aheckmann
2011-08-01 add note about native driver to README
304
c8030922 » bnoguchi
2011-04-12 Updated README with a list of available plugins.
305 ## Mongoose Plugins
306
eaa29ee9 » aheckmann
2012-08-02 Update README.md
307 Take a peek at the [plugins search site](http://plugins.mongoosejs.com/) to see related modules from the community.
c8030922 » bnoguchi
2011-04-12 Updated README with a list of available plugins.
308
55b825bd » guille
2011-01-25 Updated README and example
309 ## Contributing to Mongoose
310
311 ### Cloning the repository
312
c6593956 » aheckmann
2012-08-24 docs; fix links
313 git clone git://github.com/LearnBoost/mongoose.git
55b825bd » guille
2011-01-25 Updated README and example
314
315 ### Guidelines
316
c6593956 » aheckmann
2012-08-24 docs; fix links
317 See [contributing](http://mongoosejs.com/docs/contributing.html).
55b825bd » guille
2011-01-25 Updated README and example
318
eca6f8f7 » guille
2011-01-31 Added credits and license
319 ## Credits
320
c6593956 » aheckmann
2012-08-24 docs; fix links
321 [contributors](https://github.com/learnboost/mongoose/graphs/contributors)
eca6f8f7 » guille
2011-01-31 Added credits and license
322
323 ## License
324
2d50d64f » aheckmann
2012-02-09 updated readme
325 Copyright (c) 2010-2012 LearnBoost <dev@learnboost.com>
eca6f8f7 » guille
2011-01-31 Added credits and license
326
327 Permission is hereby granted, free of charge, to any person obtaining
328 a copy of this software and associated documentation files (the
329 'Software'), to deal in the Software without restriction, including
330 without limitation the rights to use, copy, modify, merge, publish,
331 distribute, sublicense, and/or sell copies of the Software, and to
332 permit persons to whom the Software is furnished to do so, subject to
333 the following conditions:
334
335 The above copyright notice and this permission notice shall be
336 included in all copies or substantial portions of the Software.
337
338 THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
339 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
340 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
341 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
342 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
343 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
344 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Something went wrong with that request. Please try again.