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.

321 lines
11 KiB

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