arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/mongoose/README.md
node_modules/mongoose/README.mdRaw
  1# Mongoose
  2
  3Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
  4
  5[![Build Status](https://api.travis-ci.org/Automattic/mongoose.svg?branch=master)](https://travis-ci.org/Automattic/mongoose)
  6[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
  7[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
  8[![Dependency Status](https://gemnasium.com/Automattic/mongoose.svg)](https://gemnasium.com/Automattic/mongoose)
  9
 10## Documentation
 11
 12[mongoosejs.com](http://mongoosejs.com/)
 13
 14## Support
 15
 16  - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
 17  - [bug reports](https://github.com/Automattic/mongoose/issues/)
 18  - [help forum](http://groups.google.com/group/mongoose-orm)
 19  - [MongoDB support](https://docs.mongodb.org/manual/support/)
 20  - [Mongoose Slack Channel](https://mongoosejs.slack.com/)
 21
 22## Plugins
 23
 24Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community.
 25
 26Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin).
 27
 28## Contributors
 29
 30View all 100+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md) too!
 31
 32## Live Examples
 33<a href="http://code.runnable.com/mongoose" target="_blank"><img src="http://i.imgur.com/4yNYDLI.png"></a>
 34
 35## Installation
 36
 37First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then:
 38
 39```sh
 40$ npm install mongoose
 41```
 42
 43## Stability
 44
 45The current stable branch is [master](https://github.com/Automattic/mongoose/tree/master). The [3.8.x](https://github.com/Automattic/mongoose/tree/3.8.x) branch contains legacy support for the 3.x release series, which is no longer under active development as of September 2015. The [3.8.x docs](http://mongoosejs.com/docs/3.8.x/) are still available.
 46
 47## Overview
 48
 49### Connecting to MongoDB
 50
 51First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
 52
 53Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
 54
 55```js
 56var mongoose = require('mongoose');
 57
 58mongoose.connect('mongodb://localhost/my_database');
 59```
 60
 61Once 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`.
 62
 63**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._
 64
 65**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.
 66
 67### Defining a Model
 68
 69Models are defined through the `Schema` interface.
 70
 71```js
 72var Schema = mongoose.Schema,
 73    ObjectId = Schema.ObjectId;
 74
 75var BlogPost = new Schema({
 76    author    : ObjectId,
 77    title     : String,
 78    body      : String,
 79    date      : Date
 80});
 81```
 82
 83Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
 84
 85* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
 86* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
 87* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
 88* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
 89* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
 90* [Middleware](http://mongoosejs.com/docs/middleware.html)
 91* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
 92* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
 93* [Plugins](http://mongoosejs.com/docs/plugins.html)
 94* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
 95
 96The following example shows some of these features:
 97
 98```js
 99var Comment = new Schema({
100  name: { type: String, default: 'hahaha' },
101  age: { type: Number, min: 18, index: true },
102  bio: { type: String, match: /[a-z]/ },
103  date: { type: Date, default: Date.now },
104  buff: Buffer
105});
106
107// a setter
108Comment.path('name').set(function (v) {
109  return capitalize(v);
110});
111
112// middleware
113Comment.pre('save', function (next) {
114  notify(this.get('email'));
115  next();
116});
117```
118
119Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
120
121### Accessing a Model
122
123Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
124
125```js
126var myModel = mongoose.model('ModelName');
127```
128
129Or just do it all at once
130
131```js
132var MyModel = mongoose.model('ModelName', mySchema);
133```
134
135The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use
136
137```js
138var MyModel = mongoose.model('Ticket', mySchema);
139```
140
141Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection.
142
143Once we have our model, we can then instantiate it, and save it:
144
145```js
146var instance = new MyModel();
147instance.my.key = 'hello';
148instance.save(function (err) {
149  //
150});
151```
152
153Or we can find documents from the same collection
154
155```js
156MyModel.find({}, function (err, docs) {
157  // docs.forEach
158});
159```
160
161You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
162
163**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:
164
165```js
166var conn = mongoose.createConnection('your connection string'),
167    MyModel = conn.model('ModelName', schema),
168    m = new MyModel;
169m.save(); // works
170```
171
172vs
173
174```js
175var conn = mongoose.createConnection('your connection string'),
176    MyModel = mongoose.model('ModelName', schema),
177    m = new MyModel;
178m.save(); // does not work b/c the default connection object was never connected
179```
180
181### Embedded Documents
182
183In the first example snippet, we defined a key in the Schema that looks like:
184
185```
186comments: [Comment]
187```
188
189Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:
190
191```js
192// retrieve my model
193var BlogPost = mongoose.model('BlogPost');
194
195// create a blog post
196var post = new BlogPost();
197
198// create a comment
199post.comments.push({ title: 'My comment' });
200
201post.save(function (err) {
202  if (!err) console.log('Success!');
203});
204```
205
206The same goes for removing them:
207
208```js
209BlogPost.findById(myId, function (err, post) {
210  if (!err) {
211    post.comments[0].remove();
212    post.save(function (err) {
213      // do something
214    });
215  }
216});
217```
218
219Embedded 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!
220
221
222### Middleware
223
224See the [docs](http://mongoosejs.com/docs/middleware.html) page.
225
226#### Intercepting and mutating method arguments
227
228You can intercept method arguments via middleware.
229
230For 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:
231
232```js
233schema.pre('set', function (next, path, val, typel) {
234  // `this` is the current Document
235  this.emit('set', path, val);
236
237  // Pass control to the next pre
238  next();
239});
240```
241
242Moreover, 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`:
243
244```js
245.pre(method, function firstPre (next, methodArg1, methodArg2) {
246  // Mutate methodArg1
247  next("altered-" + methodArg1.toString(), methodArg2);
248});
249
250// pre declaration is chainable
251.pre(method, function secondPre (next, methodArg1, methodArg2) {
252  console.log(methodArg1);
253  // => 'altered-originalValOfMethodArg1'
254
255  console.log(methodArg2);
256  // => 'originalValOfMethodArg2'
257
258  // Passing no arguments to `next` automatically passes along the current argument values
259  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
260  // and also equivalent to, with the example method arg
261  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
262  next();
263});
264```
265
266#### Schema gotcha
267
268`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:
269
270```js
271new Schema({
272  broken: { type: Boolean },
273    asset : {
274      name: String,
275      type: String // uh oh, it broke. asset will be interpreted as String
276    }
277});
278
279new Schema({
280  works: { type: Boolean },
281  asset: {
282    name: String,
283    type: { type: String } // works. asset is an object with a type property
284  }
285});
286```
287
288### Driver Access
289
290Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one
291notable exception that `YourModel.collection` still buffers
292commands. As such, `YourModel.collection.find()` will **not**
293return a cursor.
294
295## API Docs
296
297Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox)
298and [acquit](https://github.com/vkarpov15/acquit).
299
300## License
301
302Copyright (c) 2010 LearnBoost &lt;dev@learnboost.com&gt;
303
304Permission is hereby granted, free of charge, to any person obtaining
305a copy of this software and associated documentation files (the
306'Software'), to deal in the Software without restriction, including
307without limitation the rights to use, copy, modify, merge, publish,
308distribute, sublicense, and/or sell copies of the Software, and to
309permit persons to whom the Software is furnished to do so, subject to
310the following conditions:
311
312The above copyright notice and this permission notice shall be
313included in all copies or substantial portions of the Software.
314
315THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
316EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
317MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
318IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
319CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
320TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
321SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.