You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

269 lines
9.6 KiB

  1. ## What's Mongoose?
  2. Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
  3. ## Documentation
  4. [mongoosejs.com](http://mongoosejs.com/)
  5. ## Try it live
  6. <a href="https://runnable.com/#learnboost/mongoose/code.js/launch" target="_blank"><img src="https://runnable.com/external/styles/assets/runnablebtn.png" style="width:67px;height:25px;"></a>
  7. ## Support
  8. - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
  9. - [bug reports](https://github.com/learnboost/mongoose/issues/)
  10. - [help forum](http://groups.google.com/group/mongoose-orm)
  11. - [MongoDB support](http://www.mongodb.org/display/DOCS/Technical+Support)
  12. - (irc) #mongoosejs on freenode
  13. ## Installation
  14. First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads).
  15. $ npm install mongoose
  16. ## Plugins
  17. Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community.
  18. ## Contributors
  19. View all 90+ [contributors](https://github.com/learnboost/mongoose/graphs/contributors).
  20. ## Get Involved
  21. Stand up and be counted as a [contributor](https://github.com/LearnBoost/mongoose/blob/master/CONTRIBUTING.md) too!
  22. ## Overview
  23. ### Connecting to MongoDB
  24. 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`.
  25. Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
  26. var mongoose = require('mongoose');
  27. mongoose.connect('mongodb://localhost/my_database');
  28. 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`.
  29. **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.
  30. ### Defining a Model
  31. Models are defined through the `Schema` interface.
  32. var Schema = mongoose.Schema
  33. , ObjectId = Schema.ObjectId;
  34. var BlogPost = new Schema({
  35. author : ObjectId
  36. , title : String
  37. , body : String
  38. , date : Date
  39. });
  40. Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
  41. * [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
  42. * [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
  43. * [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
  44. * [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
  45. * [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
  46. * [Middleware](http://mongoosejs.com/docs/middleware.html)
  47. * [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
  48. * [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
  49. * [Plugins](http://mongoosejs.com/docs/plugins.html)
  50. * [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
  51. The following example shows some of these features:
  52. var Comment = new Schema({
  53. name : { type: String, default: 'hahaha' }
  54. , age : { type: Number, min: 18, index: true }
  55. , bio : { type: String, match: /[a-z]/ }
  56. , date : { type: Date, default: Date.now }
  57. , buff : Buffer
  58. });
  59. // a setter
  60. Comment.path('name').set(function (v) {
  61. return capitalize(v);
  62. });
  63. // middleware
  64. Comment.pre('save', function (next) {
  65. notify(this.get('email'));
  66. next();
  67. });
  68. Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
  69. ### Accessing a Model
  70. Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
  71. var myModel = mongoose.model('ModelName');
  72. Or just do it all at once
  73. var MyModel = mongoose.model('ModelName', mySchema);
  74. We can then instantiate it, and save it:
  75. var instance = new MyModel();
  76. instance.my.key = 'hello';
  77. instance.save(function (err) {
  78. //
  79. });
  80. Or we can find documents from the same collection
  81. MyModel.find({}, function (err, docs) {
  82. // docs.forEach
  83. });
  84. You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
  85. **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:
  86. var conn = mongoose.createConnection('your connection string');
  87. var MyModel = conn.model('ModelName', schema);
  88. var m = new MyModel;
  89. m.save() // works
  90. vs
  91. var conn = mongoose.createConnection('your connection string');
  92. var MyModel = mongoose.model('ModelName', schema);
  93. var m = new MyModel;
  94. m.save() // does not work b/c the default connection object was never connected
  95. ### Embedded Documents
  96. In the first example snippet, we defined a key in the Schema that looks like:
  97. comments: [Comments]
  98. Where `Comments` is a `Schema` we created. This means that creating embedded documents is as simple as:
  99. // retrieve my model
  100. var BlogPost = mongoose.model('BlogPost');
  101. // create a blog post
  102. var post = new BlogPost();
  103. // create a comment
  104. post.comments.push({ title: 'My comment' });
  105. post.save(function (err) {
  106. if (!err) console.log('Success!');
  107. });
  108. The same goes for removing them:
  109. BlogPost.findById(myId, function (err, post) {
  110. if (!err) {
  111. post.comments[0].remove();
  112. post.save(function (err) {
  113. // do something
  114. });
  115. }
  116. });
  117. 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!
  118. Mongoose interacts with your embedded documents in arrays _atomically_, out of the box.
  119. ### Middleware
  120. See the [docs](http://mongoosejs.com/docs/middleware.html) page.
  121. #### Intercepting and mutating method arguments
  122. You can intercept method arguments via middleware.
  123. 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:
  124. schema.pre('set', function (next, path, val, typel) {
  125. // `this` is the current Document
  126. this.emit('set', path, val);
  127. // Pass control to the next pre
  128. next();
  129. });
  130. 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`:
  131. .pre(method, function firstPre (next, methodArg1, methodArg2) {
  132. // Mutate methodArg1
  133. next("altered-" + methodArg1.toString(), methodArg2);
  134. })
  135. // pre declaration is chainable
  136. .pre(method, function secondPre (next, methodArg1, methodArg2) {
  137. console.log(methodArg1);
  138. // => 'altered-originalValOfMethodArg1'
  139. console.log(methodArg2);
  140. // => 'originalValOfMethodArg2'
  141. // Passing no arguments to `next` automatically passes along the current argument values
  142. // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  143. // and also equivalent to, with the example method arg
  144. // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  145. next();
  146. })
  147. #### Schema gotcha
  148. `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:
  149. new Schema({
  150. broken: { type: Boolean }
  151. , asset : {
  152. name: String
  153. , type: String // uh oh, it broke. asset will be interpreted as String
  154. }
  155. });
  156. new Schema({
  157. works: { type: Boolean }
  158. , asset : {
  159. name: String
  160. , type: { type: String } // works. asset is an object with a type property
  161. }
  162. });
  163. ### Driver access
  164. 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.
  165. ## API Docs
  166. Find the API docs [here](http://mongoosejs.com/docs/api.html), generated by [dox](http://github.com/visionmedia/dox).
  167. ## License
  168. Copyright (c) 2010 LearnBoost &lt;dev@learnboost.com&gt;
  169. Permission is hereby granted, free of charge, to any person obtaining
  170. a copy of this software and associated documentation files (the
  171. 'Software'), to deal in the Software without restriction, including
  172. without limitation the rights to use, copy, modify, merge, publish,
  173. distribute, sublicense, and/or sell copies of the Software, and to
  174. permit persons to whom the Software is furnished to do so, subject to
  175. the following conditions:
  176. The above copyright notice and this permission notice shall be
  177. included in all copies or substantial portions of the Software.
  178. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  179. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  180. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  181. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  182. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  183. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  184. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.