프로젝트

일반

사용자정보

통계
| 개정판:

root / HServer / 00.Server / 00.Program / node_modules / mongoose / README.md

이력 | 보기 | 이력해설 | 다운로드 (11.2 KB)

1
# Mongoose
2

    
3
Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
4

    
5
[![Slack Status](http://slack.mongoosejs.io/badge.svg)](http://slack.mongoosejs.io)
6
[![Build Status](https://api.travis-ci.org/Automattic/mongoose.svg?branch=master)](https://travis-ci.org/Automattic/mongoose)
7
[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
8

    
9
## Documentation
10

    
11
[mongoosejs.com](http://mongoosejs.com/)
12

    
13
[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 [GitHub](https://github.com/Automattic/mongoose/blob/master/migrating_to_5.md).
14

    
15
## Support
16

    
17
  - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
18
  - [Bug Reports](https://github.com/Automattic/mongoose/issues/)
19
  - [Mongoose Slack Channel](http://slack.mongoosejs.io/)
20
  - [Help Forum](http://groups.google.com/group/mongoose-orm)
21
  - [MongoDB Support](https://docs.mongodb.org/manual/support/)
22

    
23
## Importing
24

    
25
```javascript
26
// Using Node.js `require()`
27
const mongoose = require('mongoose');
28

    
29
// Using ES6 imports
30
import mongoose from 'mongoose';
31
```
32

    
33
## Plugins
34

    
35
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).
36

    
37
## Contributors
38

    
39
View all 300+ [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!
40

    
41
## Installation
42

    
43
First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then:
44

    
45
```sh
46
$ npm install mongoose
47
```
48

    
49
## Stability
50

    
51
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.
52

    
53
## Overview
54

    
55
### Connecting to MongoDB
56

    
57
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`.
58

    
59
Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
60

    
61
```js
62
const mongoose = require('mongoose');
63

    
64
mongoose.connect('mongodb://localhost/my_database');
65
```
66

    
67
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`.
68

    
69
**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._
70

    
71
**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.
72

    
73
### Defining a Model
74

    
75
Models are defined through the `Schema` interface.
76

    
77
```js
78
const Schema = mongoose.Schema,
79
    ObjectId = Schema.ObjectId;
80

    
81
const BlogPost = new Schema({
82
 author: ObjectId,
83
 title: String,
84
 body: String,
85
 date: Date
86
});
87
```
88

    
89
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
90

    
91
* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
92
* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
93
* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
94
* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
95
* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
96
* [Middleware](http://mongoosejs.com/docs/middleware.html)
97
* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
98
* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
99
* [Plugins](http://mongoosejs.com/docs/plugins.html)
100
* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
101

    
102
The following example shows some of these features:
103

    
104
```js
105
const Comment = new Schema({
106
  name: { type: String, default: 'hahaha' },
107
  age: { type: Number, min: 18, index: true },
108
  bio: { type: String, match: /[a-z]/ },
109
  date: { type: Date, default: Date.now },
110
  buff: Buffer
111
});
112

    
113
// a setter
114
Comment.path('name').set(function (v) {
115
  return capitalize(v);
116
});
117

    
118
// middleware
119
Comment.pre('save', function (next) {
120
  notify(this.get('email'));
121
  next();
122
});
123
```
124

    
125
Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
126

    
127
### Accessing a Model
128

    
129
Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
130

    
131
```js
132
const myModel = mongoose.model('ModelName');
133
```
134

    
135
Or just do it all at once
136

    
137
```js
138
const MyModel = mongoose.model('ModelName', mySchema);
139
```
140

    
141
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
142

    
143
```js
144
const MyModel = mongoose.model('Ticket', mySchema);
145
```
146

    
147
Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection.
148

    
149
Once we have our model, we can then instantiate it, and save it:
150

    
151
```js
152
const instance = new MyModel();
153
instance.my.key = 'hello';
154
instance.save(function (err) {
155
  //
156
});
157
```
158

    
159
Or we can find documents from the same collection
160

    
161
```js
162
MyModel.find({}, function (err, docs) {
163
  // docs.forEach
164
});
165
```
166

    
167
You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
168

    
169
**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:
170

    
171
```js
172
const conn = mongoose.createConnection('your connection string');
173
const MyModel = conn.model('ModelName', schema);
174
const m = new MyModel;
175
m.save(); // works
176
```
177

    
178
vs
179

    
180
```js
181
const conn = mongoose.createConnection('your connection string');
182
const MyModel = mongoose.model('ModelName', schema);
183
const m = new MyModel;
184
m.save(); // does not work b/c the default connection object was never connected
185
```
186

    
187
### Embedded Documents
188

    
189
In the first example snippet, we defined a key in the Schema that looks like:
190

    
191
```
192
comments: [Comment]
193
```
194

    
195
Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:
196

    
197
```js
198
// retrieve my model
199
var BlogPost = mongoose.model('BlogPost');
200

    
201
// create a blog post
202
var post = new BlogPost();
203

    
204
// create a comment
205
post.comments.push({ title: 'My comment' });
206

    
207
post.save(function (err) {
208
  if (!err) console.log('Success!');
209
});
210
```
211

    
212
The same goes for removing them:
213

    
214
```js
215
BlogPost.findById(myId, function (err, post) {
216
  if (!err) {
217
    post.comments[0].remove();
218
    post.save(function (err) {
219
      // do something
220
    });
221
  }
222
});
223
```
224

    
225
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!
226

    
227

    
228
### Middleware
229

    
230
See the [docs](http://mongoosejs.com/docs/middleware.html) page.
231

    
232
#### Intercepting and mutating method arguments
233

    
234
You can intercept method arguments via middleware.
235

    
236
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:
237

    
238
```js
239
schema.pre('set', function (next, path, val, typel) {
240
  // `this` is the current Document
241
  this.emit('set', path, val);
242

    
243
  // Pass control to the next pre
244
  next();
245
});
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
```js
251
.pre(method, function firstPre (next, methodArg1, methodArg2) {
252
  // Mutate methodArg1
253
  next("altered-" + methodArg1.toString(), methodArg2);
254
});
255

    
256
// pre declaration is chainable
257
.pre(method, function secondPre (next, methodArg1, methodArg2) {
258
  console.log(methodArg1);
259
  // => 'altered-originalValOfMethodArg1'
260

    
261
  console.log(methodArg2);
262
  // => 'originalValOfMethodArg2'
263

    
264
  // Passing no arguments to `next` automatically passes along the current argument values
265
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
266
  // and also equivalent to, with the example method arg
267
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
268
  next();
269
});
270
```
271

    
272
#### Schema gotcha
273

    
274
`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:
275

    
276
```js
277
new Schema({
278
  broken: { type: Boolean },
279
  asset: {
280
    name: String,
281
    type: String // uh oh, it broke. asset will be interpreted as String
282
  }
283
});
284

    
285
new Schema({
286
  works: { type: Boolean },
287
  asset: {
288
    name: String,
289
    type: { type: String } // works. asset is an object with a type property
290
  }
291
});
292
```
293

    
294
### Driver Access
295

    
296
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
297
notable exception that `YourModel.collection` still buffers
298
commands. As such, `YourModel.collection.find()` will **not**
299
return a cursor.
300

    
301
## API Docs
302

    
303
Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox)
304
and [acquit](https://github.com/vkarpov15/acquit).
305

    
306
## License
307

    
308
Copyright (c) 2010 LearnBoost <dev@learnboost.com>
309

    
310
Permission is hereby granted, free of charge, to any person obtaining
311
a copy of this software and associated documentation files (the
312
'Software'), to deal in the Software without restriction, including
313
without limitation the rights to use, copy, modify, merge, publish,
314
distribute, sublicense, and/or sell copies of the Software, and to
315
permit persons to whom the Software is furnished to do so, subject to
316
the following conditions:
317

    
318
The above copyright notice and this permission notice shall be
319
included in all copies or substantial portions of the Software.
320

    
321
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
322
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
323
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
324
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
325
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
326
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
327
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.