Ohm-Management - Projektarbeit B-ME
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.

README.md 11KB

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