mirror of
https://github.com/mgerb/mywebsite
synced 2026-01-12 02:42:48 +00:00
Added all files
This commit is contained in:
16
node_modules/mongoose/.npmignore
generated
vendored
Normal file
16
node_modules/mongoose/.npmignore
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
lib-cov
|
||||
**.swp
|
||||
*.sw*
|
||||
*.orig
|
||||
.DS_Store
|
||||
node_modules/
|
||||
benchmarks/
|
||||
docs/
|
||||
test/
|
||||
Makefile
|
||||
CNAME
|
||||
index.html
|
||||
index.jade
|
||||
bin/
|
||||
karma.*.js
|
||||
format_deps.js
|
||||
7
node_modules/mongoose/.travis.yml
generated
vendored
Normal file
7
node_modules/mongoose/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.12"
|
||||
- "0.10"
|
||||
- "iojs"
|
||||
services:
|
||||
- mongodb
|
||||
58
node_modules/mongoose/CONTRIBUTING.md
generated
vendored
Normal file
58
node_modules/mongoose/CONTRIBUTING.md
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
## Contributing to Mongoose
|
||||
|
||||
If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), our [Google Group](http://groups.google.com/group/mongoose-orm), or on the #mongoosejs irc channel on freenode.
|
||||
|
||||
### Reporting bugs
|
||||
|
||||
- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new).
|
||||
- Please describe the issue you are experiencing, along with any associated stack trace.
|
||||
- Please post code that reproduces the issue, the version of mongoose, node version, and mongodb version.
|
||||
- _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_.
|
||||
- In general, adding a "+1" comment to an existing issue does little to help get it resolved. A better way is to submit a well documented pull request with clean code and passing tests.
|
||||
|
||||
### Requesting new features
|
||||
|
||||
- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new).
|
||||
- Please describe a use case for it
|
||||
- it would be ideal to include test cases as well
|
||||
- In general, adding a "+1" comment to an existing issue does little to help get it resolved. A better way is to submit a well documented pull request with clean code and passing tests.
|
||||
|
||||
### Fixing bugs / Adding features
|
||||
|
||||
- Before starting to write code, look for existing [issues](https://github.com/learnboost/mongoose/issues). That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. You can create a new issue [here](https://github.com/learnboost/mongoose/issues/new).
|
||||
- _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_.
|
||||
- Fork the [repo](https://github.com/learnboost/mongoose) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
|
||||
- Follow the general coding style of the rest of the project:
|
||||
- 2 space tabs
|
||||
- no trailing whitespace
|
||||
- comma first
|
||||
- inline documentation for new methods, class members, etc
|
||||
- 1 space between conditionals/functions, and their parenthesis and curly braces
|
||||
- `if (..) {`
|
||||
- `for (..) {`
|
||||
- `while (..) {`
|
||||
- `function (err) {`
|
||||
- Write tests and make sure they pass (tests are in the [test](https://github.com/LearnBoost/mongoose/tree/master/test) directory).
|
||||
|
||||
### Running the tests
|
||||
- Open a terminal and navigate to the root of the project
|
||||
- execute `npm install` to install the necessary dependencies
|
||||
- execute `make test` to run the tests (we're using [mocha](http://visionmedia.github.com/mocha/))
|
||||
- or to execute a single test `T="-g 'some regexp that matches the test description'" make test`
|
||||
- any mocha flags can be specified with `T="..."`
|
||||
|
||||
### Documentation
|
||||
|
||||
To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/LearnBoost/mongoose/tree/master/lib) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
|
||||
|
||||
To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/LearnBoost/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here.
|
||||
|
||||
If you'd like to preview your documentation changes, first commit your changes to your local 3.8.x branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from the 3.8.x branch and builds all the static pages for you. Now execute `node static.js` from the project root which will launch a local webserver where you can browse the documentation site locally. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the 3.8.x branch with your changes.
|
||||
|
||||
### Plugins website
|
||||
|
||||
The [plugins](http://plugins.mongoosejs.com/) site is also an [open source project](https://github.com/aheckmann/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well!
|
||||
|
||||
### Sharing your projects
|
||||
|
||||
All are welcome to share their creations which use mongoose on our [tumbler](http://mongoosejs.tumblr.com/). Just fill out the [simple submission form](http://mongoosejs.tumblr.com/submit).
|
||||
2445
node_modules/mongoose/History.md
generated
vendored
Normal file
2445
node_modules/mongoose/History.md
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
318
node_modules/mongoose/README.md
generated
vendored
Normal file
318
node_modules/mongoose/README.md
generated
vendored
Normal file
@@ -0,0 +1,318 @@
|
||||
# Mongoose
|
||||
|
||||
Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
|
||||
|
||||
[](https://travis-ci.org/Automattic/mongoose)
|
||||
[](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](http://badge.fury.io/js/mongoose)
|
||||
|
||||
## Documentation
|
||||
|
||||
[mongoosejs.com](http://mongoosejs.com/)
|
||||
|
||||
## Support
|
||||
|
||||
- [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
|
||||
- [bug reports](https://github.com/Automattic/mongoose/issues/)
|
||||
- [help forum](http://groups.google.com/group/mongoose-orm)
|
||||
- [MongoDB support](http://www.mongodb.org/display/DOCS/Technical+Support)
|
||||
- (irc) #mongoosejs on freenode
|
||||
|
||||
## Plugins
|
||||
|
||||
Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community.
|
||||
|
||||
Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin).
|
||||
|
||||
## Contributors
|
||||
|
||||
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!
|
||||
|
||||
## Live Examples
|
||||
<a href="http://runnable.com/mongoose" target="_blank"><img src="http://runnable.com/external/styles/assets/runnablebtn.png" style="width:67px;height:25px;"></a>
|
||||
|
||||
## Installation
|
||||
|
||||
First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads). Then:
|
||||
|
||||
```sh
|
||||
$ npm install mongoose
|
||||
```
|
||||
|
||||
## Stability
|
||||
|
||||
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 will continue to be actively maintained until September 1, 2015.
|
||||
|
||||
## Overview
|
||||
|
||||
### Connecting to MongoDB
|
||||
|
||||
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`.
|
||||
|
||||
Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
|
||||
|
||||
```js
|
||||
var mongoose = require('mongoose');
|
||||
|
||||
mongoose.connect('mongodb://localhost/my_database');
|
||||
```
|
||||
|
||||
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`.
|
||||
|
||||
**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._
|
||||
|
||||
**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.
|
||||
|
||||
### Defining a Model
|
||||
|
||||
Models are defined through the `Schema` interface.
|
||||
|
||||
```js
|
||||
var Schema = mongoose.Schema
|
||||
, ObjectId = Schema.ObjectId;
|
||||
|
||||
var BlogPost = new Schema({
|
||||
author : ObjectId
|
||||
, title : String
|
||||
, body : String
|
||||
, date : Date
|
||||
});
|
||||
```
|
||||
|
||||
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
|
||||
|
||||
* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
|
||||
* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
|
||||
* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
|
||||
* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
|
||||
* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
|
||||
* [Middleware](http://mongoosejs.com/docs/middleware.html)
|
||||
* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
|
||||
* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
|
||||
* [Plugins](http://mongoosejs.com/docs/plugins.html)
|
||||
* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
|
||||
|
||||
The following example shows some of these features:
|
||||
|
||||
```js
|
||||
var Comment = new Schema({
|
||||
name : { type: String, default: 'hahaha' }
|
||||
, age : { type: Number, min: 18, index: true }
|
||||
, bio : { type: String, match: /[a-z]/ }
|
||||
, date : { type: Date, default: Date.now }
|
||||
, buff : Buffer
|
||||
});
|
||||
|
||||
// a setter
|
||||
Comment.path('name').set(function (v) {
|
||||
return capitalize(v);
|
||||
});
|
||||
|
||||
// middleware
|
||||
Comment.pre('save', function (next) {
|
||||
notify(this.get('email'));
|
||||
next();
|
||||
});
|
||||
```
|
||||
|
||||
Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
|
||||
|
||||
### Accessing a Model
|
||||
|
||||
Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
|
||||
|
||||
```js
|
||||
var myModel = mongoose.model('ModelName');
|
||||
```
|
||||
|
||||
Or just do it all at once
|
||||
|
||||
```js
|
||||
var MyModel = mongoose.model('ModelName', mySchema);
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
```js
|
||||
var MyModel = mongoose.model('Ticket', mySchema);
|
||||
```
|
||||
|
||||
Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection.
|
||||
|
||||
Once we have our model, we can then instantiate it, and save it:
|
||||
|
||||
```js
|
||||
var instance = new MyModel();
|
||||
instance.my.key = 'hello';
|
||||
instance.save(function (err) {
|
||||
//
|
||||
});
|
||||
```
|
||||
|
||||
Or we can find documents from the same collection
|
||||
|
||||
```js
|
||||
MyModel.find({}, function (err, docs) {
|
||||
// docs.forEach
|
||||
});
|
||||
```
|
||||
|
||||
You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
|
||||
|
||||
**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:
|
||||
|
||||
```js
|
||||
var conn = mongoose.createConnection('your connection string')
|
||||
, MyModel = conn.model('ModelName', schema)
|
||||
, m = new MyModel;
|
||||
m.save(); // works
|
||||
```
|
||||
|
||||
vs
|
||||
|
||||
```js
|
||||
var conn = mongoose.createConnection('your connection string')
|
||||
, MyModel = mongoose.model('ModelName', schema)
|
||||
, m = new MyModel;
|
||||
m.save(); // does not work b/c the default connection object was never connected
|
||||
```
|
||||
|
||||
### Embedded Documents
|
||||
|
||||
In the first example snippet, we defined a key in the Schema that looks like:
|
||||
|
||||
```
|
||||
comments: [Comments]
|
||||
```
|
||||
|
||||
Where `Comments` is a `Schema` we created. This means that creating embedded documents is as simple as:
|
||||
|
||||
```js
|
||||
// retrieve my model
|
||||
var BlogPost = mongoose.model('BlogPost');
|
||||
|
||||
// create a blog post
|
||||
var post = new BlogPost();
|
||||
|
||||
// create a comment
|
||||
post.comments.push({ title: 'My comment' });
|
||||
|
||||
post.save(function (err) {
|
||||
if (!err) console.log('Success!');
|
||||
});
|
||||
```
|
||||
|
||||
The same goes for removing them:
|
||||
|
||||
```js
|
||||
BlogPost.findById(myId, function (err, post) {
|
||||
if (!err) {
|
||||
post.comments[0].remove();
|
||||
post.save(function (err) {
|
||||
// do something
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
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!
|
||||
|
||||
Mongoose interacts with your embedded documents in arrays _atomically_, out of the box.
|
||||
|
||||
### Middleware
|
||||
|
||||
See the [docs](http://mongoosejs.com/docs/middleware.html) page.
|
||||
|
||||
#### Intercepting and mutating method arguments
|
||||
|
||||
You can intercept method arguments via middleware.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
schema.pre('set', function (next, path, val, typel) {
|
||||
// `this` is the current Document
|
||||
this.emit('set', path, val);
|
||||
|
||||
// Pass control to the next pre
|
||||
next();
|
||||
});
|
||||
```
|
||||
|
||||
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`:
|
||||
|
||||
```js
|
||||
.pre(method, function firstPre (next, methodArg1, methodArg2) {
|
||||
// Mutate methodArg1
|
||||
next("altered-" + methodArg1.toString(), methodArg2);
|
||||
});
|
||||
|
||||
// pre declaration is chainable
|
||||
.pre(method, function secondPre (next, methodArg1, methodArg2) {
|
||||
console.log(methodArg1);
|
||||
// => 'altered-originalValOfMethodArg1'
|
||||
|
||||
console.log(methodArg2);
|
||||
// => 'originalValOfMethodArg2'
|
||||
|
||||
// Passing no arguments to `next` automatically passes along the current argument values
|
||||
// i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
|
||||
// and also equivalent to, with the example method arg
|
||||
// values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
|
||||
next();
|
||||
});
|
||||
```
|
||||
|
||||
#### Schema gotcha
|
||||
|
||||
`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:
|
||||
|
||||
```js
|
||||
new Schema({
|
||||
broken: { type: Boolean }
|
||||
, asset : {
|
||||
name: String
|
||||
, type: String // uh oh, it broke. asset will be interpreted as String
|
||||
}
|
||||
});
|
||||
|
||||
new Schema({
|
||||
works: { type: Boolean }
|
||||
, asset : {
|
||||
name: String
|
||||
, type: { type: String } // works. asset is an object with a type property
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Driver access
|
||||
|
||||
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.
|
||||
|
||||
## API Docs
|
||||
|
||||
Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](http://github.com/visionmedia/dox)
|
||||
and [acquit](http://github.com/vkarpov15/acquit).
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2010 LearnBoost <dev@learnboost.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
10
node_modules/mongoose/contRun.sh
generated
vendored
Executable file
10
node_modules/mongoose/contRun.sh
generated
vendored
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
make test
|
||||
|
||||
ret=$?
|
||||
|
||||
while [ $ret == 0 ]; do
|
||||
make test
|
||||
ret=$?
|
||||
done
|
||||
41
node_modules/mongoose/examples/README.md
generated
vendored
Normal file
41
node_modules/mongoose/examples/README.md
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
This directory contains runnable sample mongoose programs.
|
||||
|
||||
To run:
|
||||
|
||||
- first install [Node.js](http://nodejs.org/)
|
||||
- from the root of the project, execute `npm install -d`
|
||||
- in the example directory, run `npm install -d`
|
||||
- from the command line, execute: `node example.js`, replacing "example.js" with the name of a program.
|
||||
|
||||
|
||||
Goal is to show:
|
||||
|
||||
- ~~global schemas~~
|
||||
- ~~GeoJSON schemas / use (with crs)~~
|
||||
- text search (once MongoDB removes the "Experimental/beta" label)
|
||||
- ~~lean queries~~
|
||||
- ~~statics~~
|
||||
- methods and statics on subdocs
|
||||
- custom types
|
||||
- ~~querybuilder~~
|
||||
- ~~promises~~
|
||||
- accessing driver collection, db
|
||||
- ~~connecting to replica sets~~
|
||||
- connecting to sharded clusters
|
||||
- enabling a fail fast mode
|
||||
- on the fly schemas
|
||||
- storing files
|
||||
- ~~map reduce~~
|
||||
- ~~aggregation~~
|
||||
- advanced hooks
|
||||
- using $elemMatch to return a subset of an array
|
||||
- query casting
|
||||
- upserts
|
||||
- pagination
|
||||
- express + mongoose session handling
|
||||
- ~~group by (use aggregation)~~
|
||||
- authentication
|
||||
- schema migration techniques
|
||||
- converting documents to plain objects (show transforms)
|
||||
- how to $unset
|
||||
|
||||
78
node_modules/mongoose/examples/aggregate/aggregate.js
generated
vendored
Normal file
78
node_modules/mongoose/examples/aggregate/aggregate.js
generated
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)), gender : "Male",
|
||||
likes : ['movies', 'games', 'dogs']},
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)), gender : "Female",
|
||||
likes : ['movies', 'birds', 'cats']},
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)), gender : "Male",
|
||||
likes : ['tv', 'games', 'rabbits']},
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)), gender : "Female",
|
||||
likes : ['books', 'cats', 'dogs']},
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)), gender : "Male",
|
||||
likes : ['glasses', 'wine', 'the night']},
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
|
||||
// run an aggregate query that will get all of the people who like a given
|
||||
// item. To see the full documentation on ways to use the aggregate
|
||||
// framework, see http://docs.mongodb.org/manual/core/aggregation/
|
||||
Person.aggregate(
|
||||
// select the fields we want to deal with
|
||||
{ $project : { name : 1, likes : 1 } },
|
||||
// unwind 'likes', which will create a document for each like
|
||||
{ $unwind : "$likes" },
|
||||
// group everything by the like and then add each name with that like to
|
||||
// the set for the like
|
||||
{ $group : {
|
||||
_id : { likes : "$likes" },
|
||||
likers : { $addToSet : "$name" }
|
||||
} },
|
||||
function (err, result) {
|
||||
if (err) throw err;
|
||||
console.log(result);
|
||||
//[ { _id: { likes: 'the night' }, likers: [ 'alucard' ] },
|
||||
//{ _id: { likes: 'wine' }, likers: [ 'alucard' ] },
|
||||
//{ _id: { likes: 'books' }, likers: [ 'lilly' ] },
|
||||
//{ _id: { likes: 'glasses' }, likers: [ 'alucard' ] },
|
||||
//{ _id: { likes: 'birds' }, likers: [ 'mary' ] },
|
||||
//{ _id: { likes: 'rabbits' }, likers: [ 'bob' ] },
|
||||
//{ _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] },
|
||||
//{ _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] },
|
||||
//{ _id: { likes: 'tv' }, likers: [ 'bob' ] },
|
||||
//{ _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] },
|
||||
//{ _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] } ]
|
||||
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
14
node_modules/mongoose/examples/aggregate/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/aggregate/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "aggregate-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for aggregate example",
|
||||
"main": "aggregate.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
17
node_modules/mongoose/examples/aggregate/person.js
generated
vendored
Normal file
17
node_modules/mongoose/examples/aggregate/person.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date,
|
||||
gender: String,
|
||||
likes: [String]
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
70
node_modules/mongoose/examples/doc-methods.js
generated
vendored
Normal file
70
node_modules/mongoose/examples/doc-methods.js
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
|
||||
var mongoose = require('mongoose')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
console.log('Running mongoose version %s', mongoose.version);
|
||||
|
||||
/**
|
||||
* Schema
|
||||
*/
|
||||
|
||||
var CharacterSchema = Schema({
|
||||
name: { type: String, required: true }
|
||||
, health: { type: Number, min: 0, max: 100 }
|
||||
})
|
||||
|
||||
/**
|
||||
* Methods
|
||||
*/
|
||||
|
||||
CharacterSchema.methods.attack = function () {
|
||||
console.log('%s is attacking', this.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Character model
|
||||
*/
|
||||
|
||||
var Character = mongoose.model('Character', CharacterSchema);
|
||||
|
||||
/**
|
||||
* Connect to the database on localhost with
|
||||
* the default port (27017)
|
||||
*/
|
||||
|
||||
var dbname = 'mongoose-example-doc-methods-' + ((Math.random()*10000)|0);
|
||||
var uri = 'mongodb://localhost/' + dbname;
|
||||
|
||||
console.log('connecting to %s', uri);
|
||||
|
||||
mongoose.connect(uri, function (err) {
|
||||
// if we failed to connect, abort
|
||||
if (err) throw err;
|
||||
|
||||
// we connected ok
|
||||
example();
|
||||
})
|
||||
|
||||
/**
|
||||
* Use case
|
||||
*/
|
||||
|
||||
function example () {
|
||||
Character.create({ name: 'Link', health: 100 }, function (err, link) {
|
||||
if (err) return done(err);
|
||||
console.log('found', link);
|
||||
link.attack(); // 'Link is attacking'
|
||||
done();
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up
|
||||
*/
|
||||
|
||||
function done (err) {
|
||||
if (err) console.error(err);
|
||||
mongoose.connection.db.dropDatabase(function () {
|
||||
mongoose.disconnect();
|
||||
})
|
||||
}
|
||||
1
node_modules/mongoose/examples/express/README.md
generated
vendored
Normal file
1
node_modules/mongoose/examples/express/README.md
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
Mongoose + Express examples
|
||||
6
node_modules/mongoose/examples/express/connection-sharing/README.md
generated
vendored
Normal file
6
node_modules/mongoose/examples/express/connection-sharing/README.md
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
|
||||
To run:
|
||||
|
||||
- Execute `npm install` from this directory
|
||||
- Execute `node app.js`
|
||||
- Navigate to `localhost:8000`
|
||||
18
node_modules/mongoose/examples/express/connection-sharing/app.js
generated
vendored
Normal file
18
node_modules/mongoose/examples/express/connection-sharing/app.js
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
|
||||
var express = require('express')
|
||||
var mongoose = require('../../../lib')
|
||||
|
||||
var uri = 'mongodb://localhost/mongoose-shared-connection';
|
||||
global.db = mongoose.createConnection(uri);
|
||||
|
||||
var routes = require('./routes')
|
||||
|
||||
var app = express();
|
||||
app.get('/', routes.home);
|
||||
app.get('/insert', routes.insert);
|
||||
app.get('/name', routes.modelName);
|
||||
|
||||
app.listen(8000, function () {
|
||||
console.log('listening on http://localhost:8000');
|
||||
})
|
||||
|
||||
6
node_modules/mongoose/examples/express/connection-sharing/modelA.js
generated
vendored
Normal file
6
node_modules/mongoose/examples/express/connection-sharing/modelA.js
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
|
||||
var Schema = require('../../../lib').Schema;
|
||||
var mySchema = Schema({ name: String });
|
||||
|
||||
// db is global
|
||||
module.exports = db.model('MyModel', mySchema);
|
||||
14
node_modules/mongoose/examples/express/connection-sharing/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/express/connection-sharing/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "connection-sharing",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "ERROR: No README.md file found!",
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "express": "3.1.1" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
20
node_modules/mongoose/examples/express/connection-sharing/routes.js
generated
vendored
Normal file
20
node_modules/mongoose/examples/express/connection-sharing/routes.js
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
var model = require('./modelA')
|
||||
|
||||
exports.home = function (req, res, next) {
|
||||
model.find(function (err, docs) {
|
||||
if (err) return next(err);
|
||||
res.send(docs);
|
||||
})
|
||||
}
|
||||
|
||||
exports.modelName = function (req, res) {
|
||||
res.send('my model name is ' + model.modelName);
|
||||
}
|
||||
|
||||
exports.insert = function (req, res, next) {
|
||||
model.create({ name: 'inserting ' + Date.now() }, function (err, doc) {
|
||||
if (err) return next(err);
|
||||
res.send(doc);
|
||||
})
|
||||
}
|
||||
22
node_modules/mongoose/examples/geospatial/geoJSONSchema.js
generated
vendored
Normal file
22
node_modules/mongoose/examples/geospatial/geoJSONSchema.js
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
// NOTE : This object must conform *precisely* to the geoJSON specification
|
||||
// you cannot embed a geoJSON doc inside a model or anything like that- IT
|
||||
// MUST BE VANILLA
|
||||
var LocationObject = new Schema({
|
||||
loc: {
|
||||
type: { type: String },
|
||||
coordinates: []
|
||||
}
|
||||
});
|
||||
// define the index
|
||||
LocationObject.index({ loc : '2dsphere' });
|
||||
|
||||
mongoose.model('Location', LocationObject);
|
||||
};
|
||||
49
node_modules/mongoose/examples/geospatial/geoJSONexample.js
generated
vendored
Normal file
49
node_modules/mongoose/examples/geospatial/geoJSONexample.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./geoJSONSchema.js')();
|
||||
|
||||
var Location = mongoose.model('Location');
|
||||
|
||||
// define some dummy data
|
||||
// note: the type can be Point, LineString, or Polygon
|
||||
var data = [
|
||||
{ loc: { type: 'Point', coordinates: [-20.0, 5.0] }},
|
||||
{ loc: { type: 'Point', coordinates: [6.0, 10.0] }},
|
||||
{ loc: { type: 'Point', coordinates: [34.0, -50.0] }},
|
||||
{ loc: { type: 'Point', coordinates: [-100.0, 70.0] }},
|
||||
{ loc: { type: 'Point', coordinates: [38.0, 38.0] }}
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/locations', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
Location.on('index', function(err) {
|
||||
if (err) throw err;
|
||||
// create all of the dummy locations
|
||||
async.each(data, function (item, cb) {
|
||||
Location.create(item, cb);
|
||||
}, function (err) {
|
||||
if (err) throw err;
|
||||
// create the location we want to search for
|
||||
var coords = { type : 'Point', coordinates : [-5, 5] };
|
||||
// search for it
|
||||
Location.find({ loc : { $near : coords }}).limit(1).exec(function(err, res) {
|
||||
if (err) throw err;
|
||||
console.log("Closest to %s is %s", JSON.stringify(coords), res);
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Location.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
67
node_modules/mongoose/examples/geospatial/geospatial.js
generated
vendored
Normal file
67
node_modules/mongoose/examples/geospatial/geospatial.js
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)), gender : "Male",
|
||||
likes : ['movies', 'games', 'dogs'], loc : [0, 0]},
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)), gender : "Female",
|
||||
likes : ['movies', 'birds', 'cats'], loc : [1, 1]},
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)), gender : "Male",
|
||||
likes : ['tv', 'games', 'rabbits'], loc : [3, 3]},
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)), gender : "Female",
|
||||
likes : ['books', 'cats', 'dogs'], loc : [6, 6]},
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)), gender : "Male",
|
||||
likes : ['glasses', 'wine', 'the night'], loc : [10, 10]},
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
|
||||
// let's find the closest person to bob
|
||||
Person.find({ name : 'bob' }, function (err, res) {
|
||||
if (err) throw err;
|
||||
|
||||
res[0].findClosest(function (err, closest) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log("%s is closest to %s", res[0].name, closest);
|
||||
|
||||
|
||||
// we can also just query straight off of the model. For more
|
||||
// information about geospatial queries and indexes, see
|
||||
// http://docs.mongodb.org/manual/applications/geospatial-indexes/
|
||||
var coords = [7,7];
|
||||
Person.find({ loc : { $nearSphere : coords }}).limit(1).exec(function(err, res) {
|
||||
console.log("Closest to %s is %s", coords, res);
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
14
node_modules/mongoose/examples/geospatial/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/geospatial/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "geospatial-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for geospatial example",
|
||||
"main": "geospatial.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
28
node_modules/mongoose/examples/geospatial/person.js
generated
vendored
Normal file
28
node_modules/mongoose/examples/geospatial/person.js
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date,
|
||||
gender: String,
|
||||
likes: [String],
|
||||
// define the geospatial field
|
||||
loc: { type : [Number], index: '2d' }
|
||||
});
|
||||
|
||||
// define a method to find the closest person
|
||||
PersonSchema.methods.findClosest = function(cb) {
|
||||
return this.model('Person').find({
|
||||
loc : { $nearSphere : this.loc },
|
||||
name : { $ne : this.name }
|
||||
}).limit(1).exec(cb);
|
||||
};
|
||||
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
40
node_modules/mongoose/examples/globalschemas/gs_example.js
generated
vendored
Normal file
40
node_modules/mongoose/examples/globalschemas/gs_example.js
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
|
||||
// import the global schema, this can be done in any file that needs the model
|
||||
require('./person.js')();
|
||||
|
||||
// grab the person model object
|
||||
var Person = mongoose.model("Person");
|
||||
|
||||
// connect to a server to do a quick write / read example
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function(err) {
|
||||
if (err) throw err;
|
||||
|
||||
Person.create({
|
||||
name : 'bill',
|
||||
age : 25,
|
||||
birthday : new Date().setFullYear((new Date().getFullYear() - 25))
|
||||
}, function (err, bill) {
|
||||
if (err) throw err;
|
||||
console.log("People added to db: %s", bill.toString());
|
||||
Person.find({}, function(err, people) {
|
||||
if (err) throw err;
|
||||
|
||||
people.forEach(function(person) {
|
||||
console.log("People in the db: %s", person.toString());
|
||||
});
|
||||
|
||||
// make sure to clean things up after we're done
|
||||
setTimeout(function () { cleanup(); }, 2000);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
15
node_modules/mongoose/examples/globalschemas/person.js
generated
vendored
Normal file
15
node_modules/mongoose/examples/globalschemas/person.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
61
node_modules/mongoose/examples/lean/lean.js
generated
vendored
Normal file
61
node_modules/mongoose/examples/lean/lean.js
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)), gender : "Male",
|
||||
likes : ['movies', 'games', 'dogs']},
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)), gender : "Female",
|
||||
likes : ['movies', 'birds', 'cats']},
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)), gender : "Male",
|
||||
likes : ['tv', 'games', 'rabbits']},
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)), gender : "Female",
|
||||
likes : ['books', 'cats', 'dogs']},
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)), gender : "Male",
|
||||
likes : ['glasses', 'wine', 'the night']},
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
|
||||
// lean queries return just plain javascript objects, not
|
||||
// MongooseDocuments. This makes them good for high performance read
|
||||
// situations
|
||||
|
||||
// when using .lean() the default is true, but you can explicitly set the
|
||||
// value by passing in a boolean value. IE. .lean(false)
|
||||
var q = Person.find({ age : { $lt : 1000 }}).sort('age').limit(2).lean();
|
||||
q.exec(function (err, results) {
|
||||
if (err) throw err;
|
||||
console.log("Are the results MongooseDocuments?: %s", results[0] instanceof mongoose.Document);
|
||||
|
||||
console.log(results);
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
14
node_modules/mongoose/examples/lean/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/lean/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "lean-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for lean example",
|
||||
"main": "lean.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
17
node_modules/mongoose/examples/lean/person.js
generated
vendored
Normal file
17
node_modules/mongoose/examples/lean/person.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date,
|
||||
gender: String,
|
||||
likes: [String]
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
77
node_modules/mongoose/examples/mapreduce/mapreduce.js
generated
vendored
Normal file
77
node_modules/mongoose/examples/mapreduce/mapreduce.js
generated
vendored
Normal file
@@ -0,0 +1,77 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)), gender : "Male" },
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)), gender : "Female" },
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)), gender : "Male" },
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)), gender : "Female" },
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)), gender : "Male" },
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
|
||||
// alright, simple map reduce example. We will find the total ages of each
|
||||
// gender
|
||||
|
||||
// create the options object
|
||||
var o = {};
|
||||
|
||||
o.map = function () {
|
||||
// in this function, 'this' refers to the current document being
|
||||
// processed. Return the (gender, age) tuple using emit()
|
||||
emit(this.gender, this.age);
|
||||
};
|
||||
|
||||
// the reduce function receives the array of ages that are grouped by the
|
||||
// id, which in this case is the gender
|
||||
o.reduce = function (id, ages) {
|
||||
return Array.sum(ages);
|
||||
};
|
||||
|
||||
// other options that can be specified
|
||||
|
||||
// o.query = { age : { $lt : 1000 }}; // the query object
|
||||
// o.limit = 3; // max number of documents
|
||||
// o.keeptemp = true; // default is false, specifies whether to keep temp data
|
||||
// o.finalize = someFunc; // function called after reduce
|
||||
// o.scope = {}; // the scope variable exposed to map/reduce/finalize
|
||||
// o.jsMode = true; // default is false, force execution to stay in JS
|
||||
o.verbose = true; // default is false, provide stats on the job
|
||||
// o.out = {}; // objects to specify where output goes, by default is
|
||||
// returned, but can also be stored in a new collection
|
||||
// see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce
|
||||
Person.mapReduce(o, function (err, results, stats) {
|
||||
console.log("map reduce took %d ms", stats.processtime);
|
||||
console.log(results);
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
14
node_modules/mongoose/examples/mapreduce/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/mapreduce/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "map-reduce-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for map reduce example",
|
||||
"main": "mapreduce.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
16
node_modules/mongoose/examples/mapreduce/person.js
generated
vendored
Normal file
16
node_modules/mongoose/examples/mapreduce/person.js
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date,
|
||||
gender: String
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
135
node_modules/mongoose/examples/population/population-across-three-collections.js
generated
vendored
Normal file
135
node_modules/mongoose/examples/population/population-across-three-collections.js
generated
vendored
Normal file
@@ -0,0 +1,135 @@
|
||||
|
||||
var assert = require('assert')
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
var ObjectId = mongoose.Types.ObjectId;
|
||||
|
||||
/**
|
||||
* Connect to the db
|
||||
*/
|
||||
|
||||
var dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random()
|
||||
mongoose.connect('localhost', dbname);
|
||||
mongoose.connection.on('error', function() {
|
||||
console.error('connection error', arguments);
|
||||
});
|
||||
|
||||
/**
|
||||
* Schemas
|
||||
*/
|
||||
|
||||
var user = new Schema({
|
||||
name: String,
|
||||
friends: [{
|
||||
type: Schema.ObjectId,
|
||||
ref: 'User'
|
||||
}]
|
||||
});
|
||||
var User = mongoose.model('User', user);
|
||||
|
||||
var blogpost = Schema({
|
||||
title: String,
|
||||
tags: [String],
|
||||
author: {
|
||||
type: Schema.ObjectId,
|
||||
ref: 'User'
|
||||
}
|
||||
})
|
||||
var BlogPost = mongoose.model('BlogPost', blogpost);
|
||||
|
||||
/**
|
||||
* example
|
||||
*/
|
||||
|
||||
mongoose.connection.on('open', function() {
|
||||
|
||||
/**
|
||||
* Generate data
|
||||
*/
|
||||
|
||||
var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId];
|
||||
var users = [];
|
||||
|
||||
users.push({
|
||||
_id: userIds[0],
|
||||
name: 'mary',
|
||||
friends: [userIds[1], userIds[2], userIds[3]]
|
||||
});
|
||||
users.push({
|
||||
_id: userIds[1],
|
||||
name: 'bob',
|
||||
friends: [userIds[0], userIds[2], userIds[3]]
|
||||
});
|
||||
users.push({
|
||||
_id: userIds[2],
|
||||
name: 'joe',
|
||||
friends: [userIds[0], userIds[1], userIds[3]]
|
||||
});
|
||||
users.push({
|
||||
_id: userIds[3],
|
||||
name: 'sally',
|
||||
friends: [userIds[0], userIds[1], userIds[2]]
|
||||
});
|
||||
|
||||
User.create(users, function(err, docs) {
|
||||
assert.ifError(err);
|
||||
|
||||
var blogposts = [];
|
||||
blogposts.push({
|
||||
title: 'blog 1',
|
||||
tags: ['fun', 'cool'],
|
||||
author: userIds[3]
|
||||
})
|
||||
blogposts.push({
|
||||
title: 'blog 2',
|
||||
tags: ['cool'],
|
||||
author: userIds[1]
|
||||
})
|
||||
blogposts.push({
|
||||
title: 'blog 3',
|
||||
tags: ['fun', 'odd'],
|
||||
author: userIds[2]
|
||||
})
|
||||
|
||||
BlogPost.create(blogposts, function(err, docs) {
|
||||
assert.ifError(err);
|
||||
|
||||
/**
|
||||
* Population
|
||||
*/
|
||||
|
||||
BlogPost
|
||||
.find({ tags: 'fun' })
|
||||
.lean()
|
||||
.populate('author')
|
||||
.exec(function(err, docs) {
|
||||
assert.ifError(err);
|
||||
|
||||
/**
|
||||
* Populate the populated documents
|
||||
*/
|
||||
|
||||
var opts = {
|
||||
path: 'author.friends',
|
||||
select: 'name',
|
||||
options: { limit: 2 }
|
||||
}
|
||||
|
||||
BlogPost.populate(docs, opts, function(err, docs) {
|
||||
assert.ifError(err);
|
||||
console.log('populated');
|
||||
var s = require('util').inspect(docs, { depth: null })
|
||||
console.log(s);
|
||||
done();
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
function done(err) {
|
||||
if (err) console.error(err.stack);
|
||||
mongoose.connection.db.dropDatabase(function() {
|
||||
mongoose.connection.close();
|
||||
});
|
||||
}
|
||||
95
node_modules/mongoose/examples/population/population-basic.js
generated
vendored
Normal file
95
node_modules/mongoose/examples/population/population-basic.js
generated
vendored
Normal file
@@ -0,0 +1,95 @@
|
||||
|
||||
var mongoose = require('../../lib')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
console.log('Running mongoose version %s', mongoose.version);
|
||||
|
||||
/**
|
||||
* Console schema
|
||||
*/
|
||||
|
||||
var consoleSchema = Schema({
|
||||
name: String
|
||||
, manufacturer: String
|
||||
, released: Date
|
||||
})
|
||||
var Console = mongoose.model('Console', consoleSchema);
|
||||
|
||||
/**
|
||||
* Game schema
|
||||
*/
|
||||
|
||||
var gameSchema = Schema({
|
||||
name: String
|
||||
, developer: String
|
||||
, released: Date
|
||||
, consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
|
||||
})
|
||||
var Game = mongoose.model('Game', gameSchema);
|
||||
|
||||
/**
|
||||
* Connect to the console database on localhost with
|
||||
* the default port (27017)
|
||||
*/
|
||||
|
||||
mongoose.connect('mongodb://localhost/console', function (err) {
|
||||
// if we failed to connect, abort
|
||||
if (err) throw err;
|
||||
|
||||
// we connected ok
|
||||
createData();
|
||||
})
|
||||
|
||||
/**
|
||||
* Data generation
|
||||
*/
|
||||
|
||||
function createData () {
|
||||
Console.create({
|
||||
name: 'Nintendo 64'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'September 29, 1996'
|
||||
}, function (err, nintendo64) {
|
||||
if (err) return done(err);
|
||||
|
||||
Game.create({
|
||||
name: 'Legend of Zelda: Ocarina of Time'
|
||||
, developer: 'Nintendo'
|
||||
, released: new Date('November 21, 1998')
|
||||
, consoles: [nintendo64]
|
||||
}, function (err) {
|
||||
if (err) return done(err);
|
||||
example();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Population
|
||||
*/
|
||||
|
||||
function example () {
|
||||
Game
|
||||
.findOne({ name: /^Legend of Zelda/ })
|
||||
.populate('consoles')
|
||||
.exec(function (err, ocinara) {
|
||||
if (err) return done(err);
|
||||
|
||||
console.log(
|
||||
'"%s" was released for the %s on %s'
|
||||
, ocinara.name
|
||||
, ocinara.consoles[0].name
|
||||
, ocinara.released.toLocaleDateString());
|
||||
|
||||
done();
|
||||
})
|
||||
}
|
||||
|
||||
function done (err) {
|
||||
if (err) console.error(err);
|
||||
Console.remove(function () {
|
||||
Game.remove(function () {
|
||||
mongoose.disconnect();
|
||||
})
|
||||
})
|
||||
}
|
||||
101
node_modules/mongoose/examples/population/population-of-existing-doc.js
generated
vendored
Normal file
101
node_modules/mongoose/examples/population/population-of-existing-doc.js
generated
vendored
Normal file
@@ -0,0 +1,101 @@
|
||||
|
||||
var mongoose = require('../../lib')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
console.log('Running mongoose version %s', mongoose.version);
|
||||
|
||||
/**
|
||||
* Console schema
|
||||
*/
|
||||
|
||||
var consoleSchema = Schema({
|
||||
name: String
|
||||
, manufacturer: String
|
||||
, released: Date
|
||||
})
|
||||
var Console = mongoose.model('Console', consoleSchema);
|
||||
|
||||
/**
|
||||
* Game schema
|
||||
*/
|
||||
|
||||
var gameSchema = Schema({
|
||||
name: String
|
||||
, developer: String
|
||||
, released: Date
|
||||
, consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
|
||||
})
|
||||
var Game = mongoose.model('Game', gameSchema);
|
||||
|
||||
/**
|
||||
* Connect to the console database on localhost with
|
||||
* the default port (27017)
|
||||
*/
|
||||
|
||||
mongoose.connect('mongodb://localhost/console', function (err) {
|
||||
// if we failed to connect, abort
|
||||
if (err) throw err;
|
||||
|
||||
// we connected ok
|
||||
createData();
|
||||
})
|
||||
|
||||
/**
|
||||
* Data generation
|
||||
*/
|
||||
|
||||
function createData () {
|
||||
Console.create({
|
||||
name: 'Nintendo 64'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'September 29, 1996'
|
||||
}, function (err, nintendo64) {
|
||||
if (err) return done(err);
|
||||
|
||||
Game.create({
|
||||
name: 'Legend of Zelda: Ocarina of Time'
|
||||
, developer: 'Nintendo'
|
||||
, released: new Date('November 21, 1998')
|
||||
, consoles: [nintendo64]
|
||||
}, function (err) {
|
||||
if (err) return done(err);
|
||||
example();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Population
|
||||
*/
|
||||
|
||||
function example () {
|
||||
Game
|
||||
.findOne({ name: /^Legend of Zelda/ })
|
||||
.exec(function (err, ocinara) {
|
||||
if (err) return done(err);
|
||||
|
||||
console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]);
|
||||
|
||||
// population of existing document
|
||||
ocinara.populate('consoles', function (err) {
|
||||
if (err) return done(err);
|
||||
|
||||
console.log(
|
||||
'"%s" was released for the %s on %s'
|
||||
, ocinara.name
|
||||
, ocinara.consoles[0].name
|
||||
, ocinara.released.toLocaleDateString());
|
||||
|
||||
done();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function done (err) {
|
||||
if (err) console.error(err);
|
||||
Console.remove(function () {
|
||||
Game.remove(function () {
|
||||
mongoose.disconnect();
|
||||
})
|
||||
})
|
||||
}
|
||||
112
node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js
generated
vendored
Normal file
112
node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js
generated
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
|
||||
var mongoose = require('../../lib')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
console.log('Running mongoose version %s', mongoose.version);
|
||||
|
||||
/**
|
||||
* Console schema
|
||||
*/
|
||||
|
||||
var consoleSchema = Schema({
|
||||
name: String
|
||||
, manufacturer: String
|
||||
, released: Date
|
||||
})
|
||||
var Console = mongoose.model('Console', consoleSchema);
|
||||
|
||||
/**
|
||||
* Game schema
|
||||
*/
|
||||
|
||||
var gameSchema = Schema({
|
||||
name: String
|
||||
, developer: String
|
||||
, released: Date
|
||||
, consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
|
||||
})
|
||||
var Game = mongoose.model('Game', gameSchema);
|
||||
|
||||
/**
|
||||
* Connect to the console database on localhost with
|
||||
* the default port (27017)
|
||||
*/
|
||||
|
||||
mongoose.connect('mongodb://localhost/console', function (err) {
|
||||
// if we failed to connect, abort
|
||||
if (err) throw err;
|
||||
|
||||
// we connected ok
|
||||
createData();
|
||||
})
|
||||
|
||||
/**
|
||||
* Data generation
|
||||
*/
|
||||
|
||||
function createData () {
|
||||
Console.create({
|
||||
name: 'Nintendo 64'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'September 29, 1996'
|
||||
}, {
|
||||
name: 'Super Nintendo'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'August 23, 1991'
|
||||
}, function (err, nintendo64, superNintendo) {
|
||||
if (err) return done(err);
|
||||
|
||||
Game.create({
|
||||
name: 'Legend of Zelda: Ocarina of Time'
|
||||
, developer: 'Nintendo'
|
||||
, released: new Date('November 21, 1998')
|
||||
, consoles: [nintendo64]
|
||||
}, {
|
||||
name: 'Mario Kart'
|
||||
, developer: 'Nintendo'
|
||||
, released: 'September 1, 1992'
|
||||
, consoles: [superNintendo]
|
||||
}, function (err) {
|
||||
if (err) return done(err);
|
||||
example();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Population
|
||||
*/
|
||||
|
||||
function example () {
|
||||
Game
|
||||
.find({})
|
||||
.exec(function (err, games) {
|
||||
if (err) return done(err);
|
||||
|
||||
console.log('found %d games', games.length);
|
||||
|
||||
var options = { path: 'consoles', select: 'name released -_id' };
|
||||
Game.populate(games, options, function (err, games) {
|
||||
if (err) return done(err);
|
||||
|
||||
games.forEach(function (game) {
|
||||
console.log(
|
||||
'"%s" was released for the %s on %s'
|
||||
, game.name
|
||||
, game.consoles[0].name
|
||||
, game.released.toLocaleDateString());
|
||||
})
|
||||
|
||||
done()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function done (err) {
|
||||
if (err) console.error(err);
|
||||
Console.remove(function () {
|
||||
Game.remove(function () {
|
||||
mongoose.disconnect();
|
||||
})
|
||||
})
|
||||
}
|
||||
124
node_modules/mongoose/examples/population/population-options.js
generated
vendored
Normal file
124
node_modules/mongoose/examples/population/population-options.js
generated
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
|
||||
var mongoose = require('../../lib')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
console.log('Running mongoose version %s', mongoose.version);
|
||||
|
||||
/**
|
||||
* Console schema
|
||||
*/
|
||||
|
||||
var consoleSchema = Schema({
|
||||
name: String
|
||||
, manufacturer: String
|
||||
, released: Date
|
||||
})
|
||||
var Console = mongoose.model('Console', consoleSchema);
|
||||
|
||||
/**
|
||||
* Game schema
|
||||
*/
|
||||
|
||||
var gameSchema = Schema({
|
||||
name: String
|
||||
, developer: String
|
||||
, released: Date
|
||||
, consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
|
||||
})
|
||||
var Game = mongoose.model('Game', gameSchema);
|
||||
|
||||
/**
|
||||
* Connect to the console database on localhost with
|
||||
* the default port (27017)
|
||||
*/
|
||||
|
||||
mongoose.connect('mongodb://localhost/console', function (err) {
|
||||
// if we failed to connect, abort
|
||||
if (err) throw err;
|
||||
|
||||
// we connected ok
|
||||
createData();
|
||||
})
|
||||
|
||||
/**
|
||||
* Data generation
|
||||
*/
|
||||
|
||||
function createData () {
|
||||
Console.create({
|
||||
name: 'Nintendo 64'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'September 29, 1996'
|
||||
}, {
|
||||
name: 'Super Nintendo'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'August 23, 1991'
|
||||
}, {
|
||||
name: 'XBOX 360'
|
||||
, manufacturer: 'Microsoft'
|
||||
, released: 'November 22, 2005'
|
||||
}, function (err, nintendo64, superNintendo, xbox360) {
|
||||
if (err) return done(err);
|
||||
|
||||
Game.create({
|
||||
name: 'Legend of Zelda: Ocarina of Time'
|
||||
, developer: 'Nintendo'
|
||||
, released: new Date('November 21, 1998')
|
||||
, consoles: [nintendo64]
|
||||
}, {
|
||||
name: 'Mario Kart'
|
||||
, developer: 'Nintendo'
|
||||
, released: 'September 1, 1992'
|
||||
, consoles: [superNintendo]
|
||||
}, {
|
||||
name: 'Perfect Dark Zero'
|
||||
, developer: 'Rare'
|
||||
, released: 'November 17, 2005'
|
||||
, consoles: [xbox360]
|
||||
}, function (err) {
|
||||
if (err) return done(err);
|
||||
example();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Population
|
||||
*/
|
||||
|
||||
function example () {
|
||||
Game
|
||||
.find({})
|
||||
.populate({
|
||||
path: 'consoles'
|
||||
, match: { manufacturer: 'Nintendo' }
|
||||
, select: 'name'
|
||||
, options: { comment: 'population' }
|
||||
})
|
||||
.exec(function (err, games) {
|
||||
if (err) return done(err);
|
||||
|
||||
games.forEach(function (game) {
|
||||
console.log(
|
||||
'"%s" was released for the %s on %s'
|
||||
, game.name
|
||||
, game.consoles.length ? game.consoles[0].name : '??'
|
||||
, game.released.toLocaleDateString());
|
||||
})
|
||||
|
||||
return done();
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up
|
||||
*/
|
||||
|
||||
function done (err) {
|
||||
if (err) console.error(err);
|
||||
Console.remove(function () {
|
||||
Game.remove(function () {
|
||||
mongoose.disconnect();
|
||||
})
|
||||
})
|
||||
}
|
||||
96
node_modules/mongoose/examples/population/population-plain-objects.js
generated
vendored
Normal file
96
node_modules/mongoose/examples/population/population-plain-objects.js
generated
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
|
||||
var mongoose = require('../../lib')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
console.log('Running mongoose version %s', mongoose.version);
|
||||
|
||||
/**
|
||||
* Console schema
|
||||
*/
|
||||
|
||||
var consoleSchema = Schema({
|
||||
name: String
|
||||
, manufacturer: String
|
||||
, released: Date
|
||||
})
|
||||
var Console = mongoose.model('Console', consoleSchema);
|
||||
|
||||
/**
|
||||
* Game schema
|
||||
*/
|
||||
|
||||
var gameSchema = Schema({
|
||||
name: String
|
||||
, developer: String
|
||||
, released: Date
|
||||
, consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
|
||||
})
|
||||
var Game = mongoose.model('Game', gameSchema);
|
||||
|
||||
/**
|
||||
* Connect to the console database on localhost with
|
||||
* the default port (27017)
|
||||
*/
|
||||
|
||||
mongoose.connect('mongodb://localhost/console', function (err) {
|
||||
// if we failed to connect, abort
|
||||
if (err) throw err;
|
||||
|
||||
// we connected ok
|
||||
createData();
|
||||
})
|
||||
|
||||
/**
|
||||
* Data generation
|
||||
*/
|
||||
|
||||
function createData () {
|
||||
Console.create({
|
||||
name: 'Nintendo 64'
|
||||
, manufacturer: 'Nintendo'
|
||||
, released: 'September 29, 1996'
|
||||
}, function (err, nintendo64) {
|
||||
if (err) return done(err);
|
||||
|
||||
Game.create({
|
||||
name: 'Legend of Zelda: Ocarina of Time'
|
||||
, developer: 'Nintendo'
|
||||
, released: new Date('November 21, 1998')
|
||||
, consoles: [nintendo64]
|
||||
}, function (err) {
|
||||
if (err) return done(err);
|
||||
example();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Population
|
||||
*/
|
||||
|
||||
function example () {
|
||||
Game
|
||||
.findOne({ name: /^Legend of Zelda/ })
|
||||
.populate('consoles')
|
||||
.lean() // just return plain objects, not documents wrapped by mongoose
|
||||
.exec(function (err, ocinara) {
|
||||
if (err) return done(err);
|
||||
|
||||
console.log(
|
||||
'"%s" was released for the %s on %s'
|
||||
, ocinara.name
|
||||
, ocinara.consoles[0].name
|
||||
, ocinara.released.toLocaleDateString());
|
||||
|
||||
done();
|
||||
})
|
||||
}
|
||||
|
||||
function done (err) {
|
||||
if (err) console.error(err);
|
||||
Console.remove(function () {
|
||||
Game.remove(function () {
|
||||
mongoose.disconnect();
|
||||
})
|
||||
})
|
||||
}
|
||||
14
node_modules/mongoose/examples/promises/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/promises/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "promise-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for promise example",
|
||||
"main": "promise.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
15
node_modules/mongoose/examples/promises/person.js
generated
vendored
Normal file
15
node_modules/mongoose/examples/promises/person.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
70
node_modules/mongoose/examples/promises/promise.js
generated
vendored
Normal file
70
node_modules/mongoose/examples/promises/promise.js
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)) },
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)) },
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)) },
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)) },
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)) },
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
|
||||
// create a promise (get one from the query builder)
|
||||
var prom = Person.find({age : { $lt : 1000 }}).exec();
|
||||
|
||||
// add a callback on the promise. This will be called on both error and
|
||||
// complete
|
||||
prom.addBack(function () { console.log("completed"); });
|
||||
|
||||
// add a callback that is only called on complete (success) events
|
||||
prom.addCallback(function () { console.log("Successful Completion!"); });
|
||||
|
||||
// add a callback that is only called on err (rejected) events
|
||||
prom.addErrback(function () { console.log("Fail Boat"); });
|
||||
|
||||
// you can chain things just like in the promise/A+ spec
|
||||
// note: each then() is returning a new promise, so the above methods
|
||||
// that we defined will all fire after the initial promise is fulfilled
|
||||
prom.then(function (people) {
|
||||
|
||||
// just getting the stuff for the next query
|
||||
var ids = people.map(function (p) {
|
||||
return p._id;
|
||||
});
|
||||
|
||||
// return the next promise
|
||||
return Person.find({ _id : { $nin : ids }}).exec();
|
||||
}).then(function (oldest) {
|
||||
console.log("Oldest person is: %s", oldest);
|
||||
}).then(cleanup);
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
14
node_modules/mongoose/examples/querybuilder/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/querybuilder/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "query-builder-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for query builder example",
|
||||
"main": "querybuilder.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
15
node_modules/mongoose/examples/querybuilder/person.js
generated
vendored
Normal file
15
node_modules/mongoose/examples/querybuilder/person.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
65
node_modules/mongoose/examples/querybuilder/querybuilder.js
generated
vendored
Normal file
65
node_modules/mongoose/examples/querybuilder/querybuilder.js
generated
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)) },
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)) },
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)) },
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)) },
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)) },
|
||||
];
|
||||
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// when querying data, instead of providing a callback, you can instead
|
||||
// leave that off and get a query object returned
|
||||
var query = Person.find({ age : { $lt : 1000 }});
|
||||
|
||||
// this allows you to continue applying modifiers to it
|
||||
query.sort('birthday');
|
||||
query.select('name');
|
||||
|
||||
// you can chain them together as well
|
||||
// a full list of methods can be found:
|
||||
// http://mongoosejs.com/docs/api.html#query-js
|
||||
query.where('age').gt(21);
|
||||
|
||||
// finally, when ready to execute the query, call the exec() function
|
||||
query.exec(function (err, results) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log(results);
|
||||
|
||||
cleanup();
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
14
node_modules/mongoose/examples/replicasets/package.json
generated
vendored
Normal file
14
node_modules/mongoose/examples/replicasets/package.json
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "replica-set-example",
|
||||
"private": "true",
|
||||
"version": "0.0.0",
|
||||
"description": "deps for replica set example",
|
||||
"main": "querybuilder.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": { "async": "*" },
|
||||
"repository": "",
|
||||
"author": "",
|
||||
"license": "BSD"
|
||||
}
|
||||
15
node_modules/mongoose/examples/replicasets/person.js
generated
vendored
Normal file
15
node_modules/mongoose/examples/replicasets/person.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date
|
||||
});
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
53
node_modules/mongoose/examples/replicasets/replica-sets.js
generated
vendored
Normal file
53
node_modules/mongoose/examples/replicasets/replica-sets.js
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
|
||||
// import async to make control flow simplier
|
||||
var async = require('async');
|
||||
|
||||
// import the rest of the normal stuff
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
require('./person.js')();
|
||||
|
||||
var Person = mongoose.model('Person');
|
||||
|
||||
// define some dummy data
|
||||
var data = [
|
||||
{ name : 'bill', age : 25, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 25)) },
|
||||
{ name : 'mary', age : 30, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 30)) },
|
||||
{ name : 'bob', age : 21, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 21)) },
|
||||
{ name : 'lilly', age : 26, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 26)) },
|
||||
{ name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
|
||||
Date().getFullYear() - 1000)) },
|
||||
];
|
||||
|
||||
|
||||
// to connect to a replica set, pass in the comma delimited uri and optionally
|
||||
// any connection options such as the rs_name.
|
||||
var opts = {
|
||||
replSet : { rs_name : "rs0" }
|
||||
};
|
||||
mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function (err) {
|
||||
if (err) throw err;
|
||||
|
||||
// create all of the dummy people
|
||||
async.each(data, function (item, cb) {
|
||||
Person.create(item, cb);
|
||||
}, function (err) {
|
||||
|
||||
// create and delete some data
|
||||
var prom = Person.find({age : { $lt : 1000 }}).exec();
|
||||
|
||||
prom.then(function (people) {
|
||||
console.log("young people: %s", people);
|
||||
}).then(cleanup);
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
102
node_modules/mongoose/examples/schema/schema.js
generated
vendored
Normal file
102
node_modules/mongoose/examples/schema/schema.js
generated
vendored
Normal file
@@ -0,0 +1,102 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var mongoose = require('../../lib')
|
||||
, Schema = mongoose.Schema;
|
||||
|
||||
/**
|
||||
* Schema definition
|
||||
*/
|
||||
|
||||
// recursive embedded-document schema
|
||||
|
||||
var Comment = new Schema();
|
||||
|
||||
Comment.add({
|
||||
title : { type: String, index: true }
|
||||
, date : Date
|
||||
, body : String
|
||||
, comments : [Comment]
|
||||
});
|
||||
|
||||
var BlogPost = new Schema({
|
||||
title : { type: String, index: true }
|
||||
, slug : { type: String, lowercase: true, trim: true }
|
||||
, date : Date
|
||||
, buf : Buffer
|
||||
, comments : [Comment]
|
||||
, creator : Schema.ObjectId
|
||||
});
|
||||
|
||||
var Person = new Schema({
|
||||
name: {
|
||||
first: String
|
||||
, last : String
|
||||
}
|
||||
, email: { type: String, required: true, index: { unique: true, sparse: true } }
|
||||
, alive: Boolean
|
||||
});
|
||||
|
||||
/**
|
||||
* Accessing a specific schema type by key
|
||||
*/
|
||||
|
||||
BlogPost.path('date')
|
||||
.default(function(){
|
||||
return new Date()
|
||||
})
|
||||
.set(function(v){
|
||||
return v == 'now' ? new Date() : v;
|
||||
});
|
||||
|
||||
/**
|
||||
* Pre hook.
|
||||
*/
|
||||
|
||||
BlogPost.pre('save', function(next, done){
|
||||
emailAuthor(done); // some async function
|
||||
next();
|
||||
});
|
||||
|
||||
/**
|
||||
* Methods
|
||||
*/
|
||||
|
||||
BlogPost.methods.findCreator = function (callback) {
|
||||
return this.db.model('Person').findById(this.creator, callback);
|
||||
}
|
||||
|
||||
BlogPost.statics.findByTitle = function (title, callback) {
|
||||
return this.find({ title: title }, callback);
|
||||
}
|
||||
|
||||
BlogPost.methods.expressiveQuery = function (creator, date, callback) {
|
||||
return this.find('creator', creator).where('date').gte(date).run(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugins
|
||||
*/
|
||||
|
||||
function slugGenerator (options){
|
||||
options = options || {};
|
||||
var key = options.key || 'title';
|
||||
|
||||
return function slugGenerator(schema){
|
||||
schema.path(key).set(function(v){
|
||||
this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, '');
|
||||
return v;
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
BlogPost.plugin(slugGenerator());
|
||||
|
||||
/**
|
||||
* Define model.
|
||||
*/
|
||||
|
||||
mongoose.model('BlogPost', BlogPost);
|
||||
mongoose.model('Person', Person);
|
||||
27
node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js
generated
vendored
Normal file
27
node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
|
||||
// modules
|
||||
var mongoose = require('../../../lib')
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// parse json
|
||||
var raw = require('./schema.json');
|
||||
|
||||
// create a schema
|
||||
var timeSignatureSchema = Schema(raw);
|
||||
|
||||
// compile the model
|
||||
var TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema);
|
||||
|
||||
// create a TimeSignature document
|
||||
var threeFour = new TimeSignature({
|
||||
count: 3
|
||||
, unit: 4
|
||||
, description: "3/4"
|
||||
, additive: false
|
||||
, created: new Date
|
||||
, links: ["http://en.wikipedia.org/wiki/Time_signature"]
|
||||
, user_id: "518d31a0ef32bbfa853a9814"
|
||||
});
|
||||
|
||||
// print its description
|
||||
console.log(threeFour)
|
||||
9
node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json
generated
vendored
Normal file
9
node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"count": "number",
|
||||
"unit": "number",
|
||||
"description": "string",
|
||||
"links": ["string"],
|
||||
"created": "date",
|
||||
"additive": "boolean",
|
||||
"user_id": "ObjectId"
|
||||
}
|
||||
21
node_modules/mongoose/examples/statics/person.js
generated
vendored
Normal file
21
node_modules/mongoose/examples/statics/person.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
|
||||
// import the necessary modules
|
||||
var mongoose = require('../../lib');
|
||||
var Schema = mongoose.Schema;
|
||||
|
||||
// create an export function to encapsulate the model creation
|
||||
module.exports = function() {
|
||||
// define schema
|
||||
var PersonSchema = new Schema({
|
||||
name : String,
|
||||
age : Number,
|
||||
birthday : Date
|
||||
});
|
||||
|
||||
// define a static
|
||||
PersonSchema.statics.findPersonByName = function (name, cb) {
|
||||
this.find({ name : new RegExp(name, 'i') }, cb);
|
||||
};
|
||||
|
||||
mongoose.model('Person', PersonSchema);
|
||||
};
|
||||
38
node_modules/mongoose/examples/statics/statics.js
generated
vendored
Normal file
38
node_modules/mongoose/examples/statics/statics.js
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
|
||||
var mongoose = require('../../lib');
|
||||
|
||||
|
||||
// import the schema
|
||||
require('./person.js')();
|
||||
|
||||
// grab the person model object
|
||||
var Person = mongoose.model("Person");
|
||||
|
||||
// connect to a server to do a quick write / read example
|
||||
|
||||
mongoose.connect('mongodb://localhost/persons', function(err) {
|
||||
if (err) throw err;
|
||||
|
||||
Person.create({
|
||||
name : 'bill',
|
||||
age : 25,
|
||||
birthday : new Date().setFullYear((new Date().getFullYear() - 25))
|
||||
}, function (err, bill) {
|
||||
if (err) throw err;
|
||||
console.log("People added to db: %s", bill.toString());
|
||||
|
||||
// using the static
|
||||
Person.findPersonByName('bill', function(err, result) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log(result);
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
Person.remove(function() {
|
||||
mongoose.disconnect();
|
||||
});
|
||||
}
|
||||
7
node_modules/mongoose/index.js
generated
vendored
Normal file
7
node_modules/mongoose/index.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
|
||||
/**
|
||||
* Export lib/mongoose
|
||||
*
|
||||
*/
|
||||
|
||||
module.exports = require('./lib/');
|
||||
488
node_modules/mongoose/lib/aggregate.js
generated
vendored
Normal file
488
node_modules/mongoose/lib/aggregate.js
generated
vendored
Normal file
@@ -0,0 +1,488 @@
|
||||
/*!
|
||||
* Module dependencies
|
||||
*/
|
||||
|
||||
var Promise = require('./promise')
|
||||
, util = require('util')
|
||||
, utils = require('./utils')
|
||||
, Query = require('./query')
|
||||
, read = Query.prototype.read
|
||||
|
||||
/**
|
||||
* Aggregate constructor used for building aggregation pipelines.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* new Aggregate();
|
||||
* new Aggregate({ $project: { a: 1, b: 1 } });
|
||||
* new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 });
|
||||
* new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]);
|
||||
*
|
||||
* Returned when calling Model.aggregate().
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* Model
|
||||
* .aggregate({ $match: { age: { $gte: 21 }}})
|
||||
* .unwind('tags')
|
||||
* .exec(callback)
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
|
||||
* - Requires MongoDB >= 2.1
|
||||
*
|
||||
* @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
|
||||
* @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate
|
||||
* @param {Object|Array} [ops] aggregation operator(s) or operator array
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Aggregate () {
|
||||
this._pipeline = [];
|
||||
this._model = undefined;
|
||||
this.options = undefined;
|
||||
|
||||
if (1 === arguments.length && util.isArray(arguments[0])) {
|
||||
this.append.apply(this, arguments[0]);
|
||||
} else {
|
||||
this.append.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds this aggregate to a model.
|
||||
*
|
||||
* @param {Model} model the model to which the aggregate is to be bound
|
||||
* @return {Aggregate}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Aggregate.prototype.bind = function (model) {
|
||||
this._model = model;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends new operators to this aggregate pipeline
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
|
||||
*
|
||||
* // or pass an array
|
||||
* var pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
|
||||
* aggregate.append(pipeline);
|
||||
*
|
||||
* @param {Object} ops operator(s) to append
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Aggregate.prototype.append = function () {
|
||||
var args = utils.args(arguments)
|
||||
, arg;
|
||||
|
||||
if (!args.every(isOperator)) {
|
||||
throw new Error("Arguments must be aggregate pipeline operators");
|
||||
}
|
||||
|
||||
this._pipeline = this._pipeline.concat(args);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a new $project operator to this aggregate pipeline.
|
||||
*
|
||||
* Mongoose query [selection syntax](#query_Query-select) is also supported.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* // include a, include b, exclude _id
|
||||
* aggregate.project("a b -_id");
|
||||
*
|
||||
* // or you may use object notation, useful when
|
||||
* // you have keys already prefixed with a "-"
|
||||
* aggregate.project({a: 1, b: 1, _id: 0});
|
||||
*
|
||||
* // reshaping documents
|
||||
* aggregate.project({
|
||||
* newField: '$b.nested'
|
||||
* , plusTen: { $add: ['$val', 10]}
|
||||
* , sub: {
|
||||
* name: '$a'
|
||||
* }
|
||||
* })
|
||||
*
|
||||
* // etc
|
||||
* aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
|
||||
*
|
||||
* @param {Object|String} arg field specification
|
||||
* @see projection http://docs.mongodb.org/manual/reference/aggregation/project/
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Aggregate.prototype.project = function (arg) {
|
||||
var fields = {};
|
||||
|
||||
if ('object' === typeof arg && !util.isArray(arg)) {
|
||||
Object.keys(arg).forEach(function (field) {
|
||||
fields[field] = arg[field];
|
||||
});
|
||||
} else if (1 === arguments.length && 'string' === typeof arg) {
|
||||
arg.split(/\s+/).forEach(function (field) {
|
||||
if (!field) return;
|
||||
var include = '-' == field[0] ? 0 : 1;
|
||||
if (include === 0) field = field.substring(1);
|
||||
fields[field] = include;
|
||||
});
|
||||
} else {
|
||||
throw new Error("Invalid project() argument. Must be string or object");
|
||||
}
|
||||
|
||||
return this.append({ $project: fields });
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a new custom $group operator to this aggregate pipeline.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.group({ _id: "$department" });
|
||||
*
|
||||
* @see $group http://docs.mongodb.org/manual/reference/aggregation/group/
|
||||
* @method group
|
||||
* @memberOf Aggregate
|
||||
* @param {Object} arg $group operator contents
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Appends a new custom $match operator to this aggregate pipeline.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.match({ department: { $in: [ "sales", "engineering" } } });
|
||||
*
|
||||
* @see $match http://docs.mongodb.org/manual/reference/aggregation/match/
|
||||
* @method match
|
||||
* @memberOf Aggregate
|
||||
* @param {Object} arg $match operator contents
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Appends a new $skip operator to this aggregate pipeline.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.skip(10);
|
||||
*
|
||||
* @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/
|
||||
* @method skip
|
||||
* @memberOf Aggregate
|
||||
* @param {Number} num number of records to skip before next stage
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Appends a new $limit operator to this aggregate pipeline.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.limit(10);
|
||||
*
|
||||
* @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/
|
||||
* @method limit
|
||||
* @memberOf Aggregate
|
||||
* @param {Number} num maximum number of records to pass to the next stage
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Appends a new $geoNear operator to this aggregate pipeline.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* **MUST** be used as the first operator in the pipeline.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.near({
|
||||
* near: [40.724, -73.997],
|
||||
* distanceField: "dist.calculated", // required
|
||||
* maxDistance: 0.008,
|
||||
* query: { type: "public" },
|
||||
* includeLocs: "dist.location",
|
||||
* uniqueDocs: true,
|
||||
* num: 5
|
||||
* });
|
||||
*
|
||||
* @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/
|
||||
* @method near
|
||||
* @memberOf Aggregate
|
||||
* @param {Object} parameters
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Aggregate.prototype.near = function (arg) {
|
||||
var op = {};
|
||||
op.$geoNear = arg;
|
||||
return this.append(op);
|
||||
};
|
||||
|
||||
/*!
|
||||
* define methods
|
||||
*/
|
||||
|
||||
'group match skip limit out'.split(' ').forEach(function ($operator) {
|
||||
Aggregate.prototype[$operator] = function (arg) {
|
||||
var op = {};
|
||||
op['$' + $operator] = arg;
|
||||
return this.append(op);
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Appends new custom $unwind operator(s) to this aggregate pipeline.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* aggregate.unwind("tags");
|
||||
* aggregate.unwind("a", "b", "c");
|
||||
*
|
||||
* @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/
|
||||
* @param {String} fields the field(s) to unwind
|
||||
* @return {Aggregate}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Aggregate.prototype.unwind = function () {
|
||||
var args = utils.args(arguments);
|
||||
|
||||
return this.append.apply(this, args.map(function (arg) {
|
||||
return { $unwind: '$' + arg };
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a new $sort operator to this aggregate pipeline.
|
||||
*
|
||||
* If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
|
||||
*
|
||||
* If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* // these are equivalent
|
||||
* aggregate.sort({ field: 'asc', test: -1 });
|
||||
* aggregate.sort('field -test');
|
||||
*
|
||||
* @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/
|
||||
* @param {Object|String} arg
|
||||
* @return {Aggregate} this
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Aggregate.prototype.sort = function (arg) {
|
||||
// TODO refactor to reuse the query builder logic
|
||||
|
||||
var sort = {};
|
||||
|
||||
if ('Object' === arg.constructor.name) {
|
||||
var desc = ['desc', 'descending', -1];
|
||||
Object.keys(arg).forEach(function (field) {
|
||||
sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
|
||||
});
|
||||
} else if (1 === arguments.length && 'string' == typeof arg) {
|
||||
arg.split(/\s+/).forEach(function (field) {
|
||||
if (!field) return;
|
||||
var ascend = '-' == field[0] ? -1 : 1;
|
||||
if (ascend === -1) field = field.substring(1);
|
||||
sort[field] = ascend;
|
||||
});
|
||||
} else {
|
||||
throw new TypeError('Invalid sort() argument. Must be a string or object.');
|
||||
}
|
||||
|
||||
return this.append({ $sort: sort });
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the readPreference option for the aggregation query.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* Model.aggregate(..).read('primaryPreferred').exec(callback)
|
||||
*
|
||||
* @param {String} pref one of the listed preference options or their aliases
|
||||
* @param {Array} [tags] optional tags for this query
|
||||
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
|
||||
* @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
|
||||
*/
|
||||
|
||||
Aggregate.prototype.read = function (pref) {
|
||||
if (!this.options) this.options = {};
|
||||
read.apply(this, arguments);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* Model.aggregate(..).allowDiskUse(true).exec(callback)
|
||||
*
|
||||
* @param {Boolean} value Should tell server it can use hard drive to store data during aggregation.
|
||||
* @param {Array} [tags] optional tags for this query
|
||||
* @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/
|
||||
*/
|
||||
|
||||
Aggregate.prototype.allowDiskUse = function(value) {
|
||||
if (!this.options) this.options = {};
|
||||
this.options.allowDiskUse = value;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the cursor option option for the aggregation query (ignored for < 2.6.0).
|
||||
* Note the different syntax below: .exec() returns a cursor object, and no callback
|
||||
* is necessary.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
|
||||
* cursor.each(function(error, doc) {
|
||||
* // use doc
|
||||
* });
|
||||
*
|
||||
* @param {Object} options set the cursor batch size
|
||||
* @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html
|
||||
*/
|
||||
|
||||
Aggregate.prototype.cursor = function(options) {
|
||||
if (!this.options) this.options = {};
|
||||
this.options.cursor = options;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Executes the aggregate pipeline on the currently bound Model.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* aggregate.exec(callback);
|
||||
*
|
||||
* // Because a promise is returned, the `callback` is optional.
|
||||
* var promise = aggregate.exec();
|
||||
* promise.then(..);
|
||||
*
|
||||
* @see Promise #promise_Promise
|
||||
* @param {Function} [callback]
|
||||
* @return {Promise}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Aggregate.prototype.exec = function (callback) {
|
||||
var promise = new Promise();
|
||||
|
||||
if (callback) {
|
||||
promise.addBack(callback);
|
||||
}
|
||||
|
||||
if (!this._pipeline.length) {
|
||||
promise.error(new Error("Aggregate has empty pipeline"));
|
||||
return promise;
|
||||
}
|
||||
|
||||
if (!this._model) {
|
||||
promise.error(new Error("Aggregate not bound to any Model"));
|
||||
return promise;
|
||||
}
|
||||
|
||||
prepareDiscriminatorPipeline(this);
|
||||
|
||||
if (this.options && this.options.cursor) {
|
||||
return this._model.collection.aggregate(this._pipeline, this.options || {});
|
||||
}
|
||||
|
||||
this._model
|
||||
.collection
|
||||
.aggregate(this._pipeline, this.options || {}, promise.resolve.bind(promise));
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Helpers
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks whether an object is likely a pipeline operator
|
||||
*
|
||||
* @param {Object} obj object to check
|
||||
* @return {Boolean}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function isOperator (obj) {
|
||||
var k;
|
||||
|
||||
if ('object' !== typeof obj) {
|
||||
return false;
|
||||
}
|
||||
|
||||
k = Object.keys(obj);
|
||||
|
||||
return 1 === k.length && k.some(function (key) {
|
||||
return '$' === key[0];
|
||||
});
|
||||
}
|
||||
|
||||
/*!
|
||||
* Adds the appropriate `$match` pipeline step to the top of an aggregate's
|
||||
* pipeline, should it's model is a non-root discriminator type. This is
|
||||
* analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`.
|
||||
*
|
||||
* @param {Aggregate} aggregate Aggregate to prepare
|
||||
*/
|
||||
|
||||
function prepareDiscriminatorPipeline (aggregate) {
|
||||
var schema = aggregate._model.schema,
|
||||
discriminatorMapping = schema && schema.discriminatorMapping;
|
||||
|
||||
if (discriminatorMapping && !discriminatorMapping.isRoot) {
|
||||
var originalPipeline = aggregate._pipeline,
|
||||
discriminatorKey = discriminatorMapping.key,
|
||||
discriminatorValue = discriminatorMapping.value;
|
||||
|
||||
// If the first pipeline stage is a match and it doesn't specify a `__t`
|
||||
// key, add the discriminator key to it. This allows for potential
|
||||
// aggregation query optimizations not to be disturbed by this feature.
|
||||
if (originalPipeline[0] && originalPipeline[0].$match &&
|
||||
!originalPipeline[0].$match[discriminatorKey]) {
|
||||
originalPipeline[0].$match[discriminatorKey] = discriminatorValue;
|
||||
// `originalPipeline` is a ref, so there's no need for
|
||||
// aggregate._pipeline = originalPipeline
|
||||
} else {
|
||||
var match = {};
|
||||
match[discriminatorKey] = discriminatorValue;
|
||||
aggregate._pipeline = [{ $match: match }].concat(originalPipeline);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
* Exports
|
||||
*/
|
||||
|
||||
module.exports = Aggregate;
|
||||
97
node_modules/mongoose/lib/browser.js
generated
vendored
Normal file
97
node_modules/mongoose/lib/browser.js
generated
vendored
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* The [MongooseError](#error_MongooseError) constructor.
|
||||
*
|
||||
* @method Error
|
||||
* @api public
|
||||
*/
|
||||
|
||||
exports.Error = require('./error');
|
||||
|
||||
/**
|
||||
* The Mongoose [Schema](#schema_Schema) constructor
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* var Schema = mongoose.Schema;
|
||||
* var CatSchema = new Schema(..);
|
||||
*
|
||||
* @method Schema
|
||||
* @api public
|
||||
*/
|
||||
|
||||
exports.Schema = require('./schema');
|
||||
|
||||
/**
|
||||
* The various Mongoose Types.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* var array = mongoose.Types.Array;
|
||||
*
|
||||
* ####Types:
|
||||
*
|
||||
* - [ObjectId](#types-objectid-js)
|
||||
* - [Buffer](#types-buffer-js)
|
||||
* - [SubDocument](#types-embedded-js)
|
||||
* - [Array](#types-array-js)
|
||||
* - [DocumentArray](#types-documentarray-js)
|
||||
*
|
||||
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
|
||||
*
|
||||
* var ObjectId = mongoose.Types.ObjectId;
|
||||
* var id1 = new ObjectId;
|
||||
*
|
||||
* @property Types
|
||||
* @api public
|
||||
*/
|
||||
exports.Types = require('./types');
|
||||
|
||||
/**
|
||||
* The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
|
||||
*
|
||||
* @method VirtualType
|
||||
* @api public
|
||||
*/
|
||||
exports.VirtualType = require('./virtualtype');
|
||||
|
||||
/**
|
||||
* The various Mongoose SchemaTypes.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _Alias of mongoose.Schema.Types for backwards compatibility._
|
||||
*
|
||||
* @property SchemaTypes
|
||||
* @see Schema.SchemaTypes #schema_Schema.Types
|
||||
* @api public
|
||||
*/
|
||||
|
||||
exports.SchemaType = require('./schematype.js');
|
||||
|
||||
/**
|
||||
* Internal utils
|
||||
*
|
||||
* @property utils
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.utils = require('./utils.js');
|
||||
|
||||
/**
|
||||
* The Mongoose browser [Document](#document-js) constructor.
|
||||
*
|
||||
* @method Document
|
||||
* @api public
|
||||
*/
|
||||
exports.Document = require('./document_provider.js')();
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.mongoose = module.exports;
|
||||
window.Buffer = Buffer;
|
||||
}
|
||||
117
node_modules/mongoose/lib/browserDocument.js
generated
vendored
Normal file
117
node_modules/mongoose/lib/browserDocument.js
generated
vendored
Normal file
@@ -0,0 +1,117 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var NodeJSDocument = require('./document')
|
||||
, EventEmitter = require('events').EventEmitter
|
||||
, setMaxListeners = EventEmitter.prototype.setMaxListeners
|
||||
, MongooseError = require('./error')
|
||||
, MixedSchema = require('./schema/mixed')
|
||||
, Schema = require('./schema')
|
||||
, ObjectId = require('./types/objectid')
|
||||
, ValidatorError = require('./schematype').ValidatorError
|
||||
, utils = require('./utils')
|
||||
, clone = utils.clone
|
||||
, isMongooseObject = utils.isMongooseObject
|
||||
, inspect = require('util').inspect
|
||||
, ValidationError = MongooseError.ValidationError
|
||||
, InternalCache = require('./internal')
|
||||
, deepEqual = utils.deepEqual
|
||||
, hooks = require('hooks-fixed')
|
||||
, Promise = require('./promise')
|
||||
, DocumentArray
|
||||
, MongooseArray
|
||||
, Embedded
|
||||
|
||||
/**
|
||||
* Document constructor.
|
||||
*
|
||||
* @param {Object} obj the values to set
|
||||
* @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
|
||||
* @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
|
||||
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
|
||||
* @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.
|
||||
* @event `save`: Emitted when the document is successfully saved
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Document (obj, schema, fields, skipId, skipInit) {
|
||||
if ( !(this instanceof Document) )
|
||||
return new Document( obj, schema, fields, skipId, skipInit );
|
||||
|
||||
|
||||
if (utils.isObject(schema) && !(schema instanceof Schema)) {
|
||||
schema = new Schema(schema);
|
||||
}
|
||||
|
||||
// When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
|
||||
schema = this.schema || schema;
|
||||
|
||||
// Generate ObjectId if it is missing, but it requires a scheme
|
||||
if ( !this.schema && schema.options._id ){
|
||||
obj = obj || {};
|
||||
|
||||
if ( obj._id === undefined ){
|
||||
obj._id = new ObjectId();
|
||||
}
|
||||
}
|
||||
|
||||
if ( !schema ){
|
||||
throw new MongooseError.MissingSchemaError();
|
||||
}
|
||||
|
||||
this.$__setSchema(schema);
|
||||
|
||||
this.$__ = new InternalCache;
|
||||
this.$__.emitter = new EventEmitter();
|
||||
this.isNew = true;
|
||||
this.errors = undefined;
|
||||
|
||||
//var schema = this.schema;
|
||||
|
||||
if ('boolean' === typeof fields) {
|
||||
this.$__.strictMode = fields;
|
||||
fields = undefined;
|
||||
} else {
|
||||
this.$__.strictMode = this.schema.options && this.schema.options.strict;
|
||||
this.$__.selected = fields;
|
||||
}
|
||||
|
||||
var required = this.schema.requiredPaths();
|
||||
for (var i = 0; i < required.length; ++i) {
|
||||
this.$__.activePaths.require(required[i]);
|
||||
}
|
||||
|
||||
setMaxListeners.call(this, 0);
|
||||
this._doc = this.$__buildDoc(obj, fields, skipId);
|
||||
|
||||
if ( !skipInit && obj ){
|
||||
this.init( obj );
|
||||
}
|
||||
|
||||
this.$__registerHooksFromSchema();
|
||||
|
||||
// apply methods
|
||||
for ( var m in schema.methods ){
|
||||
this[ m ] = schema.methods[ m ];
|
||||
}
|
||||
// apply statics
|
||||
for ( var s in schema.statics ){
|
||||
this[ s ] = schema.statics[ s ];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherit from the NodeJS document
|
||||
*/
|
||||
Document.prototype = Object.create(NodeJSDocument.prototype);
|
||||
Document.prototype.constructor = Document;
|
||||
|
||||
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
Document.ValidationError = ValidationError;
|
||||
module.exports = exports = Document;
|
||||
207
node_modules/mongoose/lib/cast.js
generated
vendored
Normal file
207
node_modules/mongoose/lib/cast.js
generated
vendored
Normal file
@@ -0,0 +1,207 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utils = require('./utils');
|
||||
var Types = require('./schema/index');
|
||||
|
||||
/**
|
||||
* Handles internal casting for queries
|
||||
*
|
||||
* @param {Schema} schema
|
||||
* @param {Object obj Object to cast
|
||||
* @api private
|
||||
*/
|
||||
|
||||
var cast = module.exports = function(schema, obj) {
|
||||
var paths = Object.keys(obj)
|
||||
, i = paths.length
|
||||
, any$conditionals
|
||||
, schematype
|
||||
, nested
|
||||
, path
|
||||
, type
|
||||
, val;
|
||||
|
||||
while (i--) {
|
||||
path = paths[i];
|
||||
val = obj[path];
|
||||
|
||||
if ('$or' === path || '$nor' === path || '$and' === path) {
|
||||
var k = val.length;
|
||||
var orComponentQuery;
|
||||
|
||||
while (k--) {
|
||||
val[k] = cast(schema, val[k]);
|
||||
}
|
||||
|
||||
} else if (path === '$where') {
|
||||
type = typeof val;
|
||||
|
||||
if ('string' !== type && 'function' !== type) {
|
||||
throw new Error("Must have a string or function for $where");
|
||||
}
|
||||
|
||||
if ('function' === type) {
|
||||
obj[path] = val.toString();
|
||||
}
|
||||
|
||||
continue;
|
||||
|
||||
} else {
|
||||
|
||||
if (!schema) {
|
||||
// no casting for Mixed types
|
||||
continue;
|
||||
}
|
||||
|
||||
schematype = schema.path(path);
|
||||
|
||||
if (!schematype) {
|
||||
// Handle potential embedded array queries
|
||||
var split = path.split('.')
|
||||
, j = split.length
|
||||
, pathFirstHalf
|
||||
, pathLastHalf
|
||||
, remainingConds
|
||||
, castingQuery;
|
||||
|
||||
// Find the part of the var path that is a path of the Schema
|
||||
while (j--) {
|
||||
pathFirstHalf = split.slice(0, j).join('.');
|
||||
schematype = schema.path(pathFirstHalf);
|
||||
if (schematype) break;
|
||||
}
|
||||
|
||||
// If a substring of the input path resolves to an actual real path...
|
||||
if (schematype) {
|
||||
// Apply the casting; similar code for $elemMatch in schema/array.js
|
||||
if (schematype.caster && schematype.caster.schema) {
|
||||
remainingConds = {};
|
||||
pathLastHalf = split.slice(j).join('.');
|
||||
remainingConds[pathLastHalf] = val;
|
||||
obj[path] = cast(schematype.caster.schema, remainingConds)[pathLastHalf];
|
||||
} else {
|
||||
obj[path] = val;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (utils.isObject(val)) {
|
||||
// handle geo schemas that use object notation
|
||||
// { loc: { long: Number, lat: Number }
|
||||
|
||||
var geo = val.$near ? '$near' :
|
||||
val.$nearSphere ? '$nearSphere' :
|
||||
val.$within ? '$within' :
|
||||
val.$geoIntersects ? '$geoIntersects' : '';
|
||||
|
||||
if (!geo) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var numbertype = new Types.Number('__QueryCasting__')
|
||||
var value = val[geo];
|
||||
|
||||
if (val.$maxDistance) {
|
||||
val.$maxDistance = numbertype.castForQuery(val.$maxDistance);
|
||||
}
|
||||
|
||||
if ('$within' == geo) {
|
||||
var withinType = value.$center
|
||||
|| value.$centerSphere
|
||||
|| value.$box
|
||||
|| value.$polygon;
|
||||
|
||||
if (!withinType) {
|
||||
throw new Error('Bad $within paramater: ' + JSON.stringify(val));
|
||||
}
|
||||
|
||||
value = withinType;
|
||||
|
||||
} else if ('$near' == geo &&
|
||||
'string' == typeof value.type && Array.isArray(value.coordinates)) {
|
||||
// geojson; cast the coordinates
|
||||
value = value.coordinates;
|
||||
|
||||
} else if (('$near' == geo || '$nearSphere' == geo || '$geoIntersects' == geo) &&
|
||||
value.$geometry && 'string' == typeof value.$geometry.type &&
|
||||
Array.isArray(value.$geometry.coordinates)) {
|
||||
// geojson; cast the coordinates
|
||||
value = value.$geometry.coordinates;
|
||||
}
|
||||
|
||||
;(function _cast (val) {
|
||||
if (Array.isArray(val)) {
|
||||
val.forEach(function (item, i) {
|
||||
if (Array.isArray(item) || utils.isObject(item)) {
|
||||
return _cast(item);
|
||||
}
|
||||
val[i] = numbertype.castForQuery(item);
|
||||
});
|
||||
} else {
|
||||
var nearKeys= Object.keys(val);
|
||||
var nearLen = nearKeys.length;
|
||||
while (nearLen--) {
|
||||
var nkey = nearKeys[nearLen];
|
||||
var item = val[nkey];
|
||||
if (Array.isArray(item) || utils.isObject(item)) {
|
||||
_cast(item);
|
||||
val[nkey] = item;
|
||||
} else {
|
||||
val[nkey] = numbertype.castForQuery(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
})(value);
|
||||
}
|
||||
|
||||
} else if (val === null || val === undefined) {
|
||||
continue;
|
||||
} else if ('Object' === val.constructor.name) {
|
||||
|
||||
any$conditionals = Object.keys(val).some(function (k) {
|
||||
return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
|
||||
});
|
||||
|
||||
if (!any$conditionals) {
|
||||
obj[path] = schematype.castForQuery(val);
|
||||
} else {
|
||||
|
||||
var ks = Object.keys(val)
|
||||
, k = ks.length
|
||||
, $cond;
|
||||
|
||||
while (k--) {
|
||||
$cond = ks[k];
|
||||
nested = val[$cond];
|
||||
|
||||
if ('$exists' === $cond) {
|
||||
if ('boolean' !== typeof nested) {
|
||||
throw new Error("$exists parameter must be Boolean");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('$type' === $cond) {
|
||||
if ('number' !== typeof nested) {
|
||||
throw new Error("$type parameter must be Number");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('$not' === $cond) {
|
||||
cast(schema, nested);
|
||||
} else {
|
||||
val[$cond] = schematype.castForQuery($cond, nested);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
obj[path] = schematype.castForQuery(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
198
node_modules/mongoose/lib/collection.js
generated
vendored
Normal file
198
node_modules/mongoose/lib/collection.js
generated
vendored
Normal file
@@ -0,0 +1,198 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var STATES = require('./connectionstate')
|
||||
|
||||
/**
|
||||
* Abstract Collection constructor
|
||||
*
|
||||
* This is the base class that drivers inherit from and implement.
|
||||
*
|
||||
* @param {String} name name of the collection
|
||||
* @param {Connection} conn A MongooseConnection instance
|
||||
* @param {Object} opts optional collection options
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Collection (name, conn, opts) {
|
||||
if (undefined === opts) opts = {};
|
||||
if (undefined === opts.capped) opts.capped = {};
|
||||
|
||||
opts.bufferCommands = undefined === opts.bufferCommands
|
||||
? true
|
||||
: opts.bufferCommands;
|
||||
|
||||
if ('number' == typeof opts.capped) {
|
||||
opts.capped = { size: opts.capped };
|
||||
}
|
||||
|
||||
this.opts = opts;
|
||||
this.name = name;
|
||||
this.collectionName = name;
|
||||
this.conn = conn;
|
||||
this.queue = [];
|
||||
this.buffer = this.opts.bufferCommands;
|
||||
|
||||
if (STATES.connected == this.conn.readyState) {
|
||||
this.onOpen();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The collection name
|
||||
*
|
||||
* @api public
|
||||
* @property name
|
||||
*/
|
||||
|
||||
Collection.prototype.name;
|
||||
|
||||
/**
|
||||
* The collection name
|
||||
*
|
||||
* @api public
|
||||
* @property collectionName
|
||||
*/
|
||||
|
||||
Collection.prototype.collectionName;
|
||||
|
||||
/**
|
||||
* The Connection instance
|
||||
*
|
||||
* @api public
|
||||
* @property conn
|
||||
*/
|
||||
|
||||
Collection.prototype.conn;
|
||||
|
||||
/**
|
||||
* Called when the database connects
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Collection.prototype.onOpen = function () {
|
||||
var self = this;
|
||||
this.buffer = false;
|
||||
self.doQueue();
|
||||
};
|
||||
|
||||
/**
|
||||
* Called when the database disconnects
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Collection.prototype.onClose = function () {
|
||||
if (this.opts.bufferCommands) {
|
||||
this.buffer = true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Queues a method for later execution when its
|
||||
* database connection opens.
|
||||
*
|
||||
* @param {String} name name of the method to queue
|
||||
* @param {Array} args arguments to pass to the method when executed
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Collection.prototype.addQueue = function (name, args) {
|
||||
this.queue.push([name, args]);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Executes all queued methods and clears the queue.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Collection.prototype.doQueue = function () {
|
||||
for (var i = 0, l = this.queue.length; i < l; i++){
|
||||
this[this.queue[i][0]].apply(this, this.queue[i][1]);
|
||||
}
|
||||
this.queue = [];
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.ensureIndex = function(){
|
||||
throw new Error('Collection#ensureIndex unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.findAndModify = function(){
|
||||
throw new Error('Collection#findAndModify unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.findOne = function(){
|
||||
throw new Error('Collection#findOne unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.find = function(){
|
||||
throw new Error('Collection#find unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.insert = function(){
|
||||
throw new Error('Collection#insert unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.save = function(){
|
||||
throw new Error('Collection#save unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.update = function(){
|
||||
throw new Error('Collection#update unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.getIndexes = function(){
|
||||
throw new Error('Collection#getIndexes unimplemented by driver');
|
||||
};
|
||||
|
||||
/**
|
||||
* Abstract method that drivers must implement.
|
||||
*/
|
||||
|
||||
Collection.prototype.mapReduce = function(){
|
||||
throw new Error('Collection#mapReduce unimplemented by driver');
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = Collection;
|
||||
700
node_modules/mongoose/lib/connection.js
generated
vendored
Normal file
700
node_modules/mongoose/lib/connection.js
generated
vendored
Normal file
@@ -0,0 +1,700 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var url = require('url')
|
||||
, utils = require('./utils')
|
||||
, EventEmitter = require('events').EventEmitter
|
||||
, driver = global.MONGOOSE_DRIVER_PATH || 'node-mongodb-native'
|
||||
, Model = require('./model')
|
||||
, Schema = require('./schema')
|
||||
, Collection = require('./drivers/' + driver + '/collection')
|
||||
, STATES = require('./connectionstate')
|
||||
, MongooseError = require('./error')
|
||||
, assert =require('assert')
|
||||
, muri = require('muri')
|
||||
|
||||
/*!
|
||||
* Protocol prefix regexp.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
var rgxProtocol = /^(?:.)+:\/\//;
|
||||
|
||||
/**
|
||||
* Connection constructor
|
||||
*
|
||||
* For practical reasons, a Connection equals a Db.
|
||||
*
|
||||
* @param {Mongoose} base a mongoose instance
|
||||
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
|
||||
* @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection.
|
||||
* @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
|
||||
* @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.
|
||||
* @event `disconnecting`: Emitted when `connection.close()` was executed.
|
||||
* @event `disconnected`: Emitted after getting disconnected from the db.
|
||||
* @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.
|
||||
* @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection.
|
||||
* @event `error`: Emitted when an error occurs on this connection.
|
||||
* @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Connection (base) {
|
||||
this.base = base;
|
||||
this.collections = {};
|
||||
this.models = {};
|
||||
this.config = {autoIndex: true};
|
||||
this.replica = false;
|
||||
this.hosts = null;
|
||||
this.host = null;
|
||||
this.port = null;
|
||||
this.user = null;
|
||||
this.pass = null;
|
||||
this.name = null;
|
||||
this.options = null;
|
||||
this.otherDbs = [];
|
||||
this._readyState = STATES.disconnected;
|
||||
this._closeCalled = false;
|
||||
this._hasOpened = false;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherit from EventEmitter
|
||||
*/
|
||||
|
||||
Connection.prototype.__proto__ = EventEmitter.prototype;
|
||||
|
||||
/**
|
||||
* Connection ready state
|
||||
*
|
||||
* - 0 = disconnected
|
||||
* - 1 = connected
|
||||
* - 2 = connecting
|
||||
* - 3 = disconnecting
|
||||
*
|
||||
* Each state change emits its associated event name.
|
||||
*
|
||||
* ####Example
|
||||
*
|
||||
* conn.on('connected', callback);
|
||||
* conn.on('disconnected', callback);
|
||||
*
|
||||
* @property readyState
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Object.defineProperty(Connection.prototype, 'readyState', {
|
||||
get: function(){ return this._readyState; }
|
||||
, set: function (val) {
|
||||
if (!(val in STATES)) {
|
||||
throw new Error('Invalid connection state: ' + val);
|
||||
}
|
||||
|
||||
if (this._readyState !== val) {
|
||||
this._readyState = val;
|
||||
// loop over the otherDbs on this connection and change their state
|
||||
for (var i=0; i < this.otherDbs.length; i++) {
|
||||
this.otherDbs[i].readyState = val;
|
||||
}
|
||||
|
||||
if (STATES.connected === val)
|
||||
this._hasOpened = true;
|
||||
|
||||
this.emit(STATES[val]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* A hash of the collections associated with this connection
|
||||
*
|
||||
* @property collections
|
||||
*/
|
||||
|
||||
Connection.prototype.collections;
|
||||
|
||||
/**
|
||||
* The mongodb.Db instance, set when the connection is opened
|
||||
*
|
||||
* @property db
|
||||
*/
|
||||
|
||||
Connection.prototype.db;
|
||||
|
||||
/**
|
||||
* A hash of the global options that are associated with this connection
|
||||
*
|
||||
* @property global
|
||||
*/
|
||||
|
||||
Connection.prototype.config;
|
||||
|
||||
/**
|
||||
* Opens the connection to MongoDB.
|
||||
*
|
||||
* `options` is a hash with the following possible properties:
|
||||
*
|
||||
* config - passed to the connection config instance
|
||||
* db - passed to the connection db instance
|
||||
* server - passed to the connection server instance(s)
|
||||
* replset - passed to the connection ReplSet instance
|
||||
* user - username for authentication
|
||||
* pass - password for authentication
|
||||
* auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
|
||||
*
|
||||
* ####Notes:
|
||||
*
|
||||
* Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
|
||||
* Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
|
||||
* See the node-mongodb-native driver instance for options that it understands.
|
||||
*
|
||||
* _Options passed take precedence over options included in connection strings._
|
||||
*
|
||||
* @param {String} connection_string mongodb://uri or the host to which you are connecting
|
||||
* @param {String} [database] database name
|
||||
* @param {Number} [port] database port
|
||||
* @param {Object} [options] options
|
||||
* @param {Function} [callback]
|
||||
* @see node-mongodb-native https://github.com/mongodb/node-mongodb-native
|
||||
* @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.open = function (host, database, port, options, callback) {
|
||||
var self = this
|
||||
, parsed
|
||||
, uri;
|
||||
|
||||
if ('string' === typeof database) {
|
||||
switch (arguments.length) {
|
||||
case 2:
|
||||
port = 27017;
|
||||
case 3:
|
||||
switch (typeof port) {
|
||||
case 'function':
|
||||
callback = port, port = 27017;
|
||||
break;
|
||||
case 'object':
|
||||
options = port, port = 27017;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
if ('function' === typeof options)
|
||||
callback = options, options = {};
|
||||
}
|
||||
} else {
|
||||
switch (typeof database) {
|
||||
case 'function':
|
||||
callback = database, database = undefined;
|
||||
break;
|
||||
case 'object':
|
||||
options = database;
|
||||
database = undefined;
|
||||
callback = port;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!rgxProtocol.test(host)) {
|
||||
host = 'mongodb://' + host;
|
||||
}
|
||||
|
||||
try {
|
||||
parsed = muri(host);
|
||||
} catch (err) {
|
||||
this.error(err, callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
database = parsed.db;
|
||||
host = parsed.hosts[0].host || parsed.hosts[0].ipc;
|
||||
port = parsed.hosts[0].port || 27017;
|
||||
}
|
||||
|
||||
this.options = this.parseOptions(options, parsed && parsed.options);
|
||||
|
||||
// make sure we can open
|
||||
if (STATES.disconnected !== this.readyState) {
|
||||
var err = new Error('Trying to open unclosed connection.');
|
||||
err.state = this.readyState;
|
||||
this.error(err, callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
if (!host) {
|
||||
this.error(new Error('Missing hostname.'), callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
if (!database) {
|
||||
this.error(new Error('Missing database name.'), callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
// authentication
|
||||
if (options && options.user && options.pass) {
|
||||
this.user = options.user;
|
||||
this.pass = options.pass;
|
||||
|
||||
} else if (parsed && parsed.auth) {
|
||||
this.user = parsed.auth.user;
|
||||
this.pass = parsed.auth.pass;
|
||||
|
||||
// Check hostname for user/pass
|
||||
} else if (/@/.test(host) && /:/.test(host.split('@')[0])) {
|
||||
host = host.split('@');
|
||||
var auth = host.shift().split(':');
|
||||
host = host.pop();
|
||||
this.user = auth[0];
|
||||
this.pass = auth[1];
|
||||
|
||||
} else {
|
||||
this.user = this.pass = undefined;
|
||||
}
|
||||
|
||||
// global configuration options
|
||||
if (options && options.config) {
|
||||
if (options.config.autoIndex === false){
|
||||
this.config.autoIndex = false;
|
||||
}
|
||||
else {
|
||||
this.config.autoIndex = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
this.name = database;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
|
||||
this._open(callback);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Opens the connection to a replica set.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var db = mongoose.createConnection();
|
||||
* db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019");
|
||||
*
|
||||
* The database name and/or auth need only be included in one URI.
|
||||
* The `options` is a hash which is passed to the internal driver connection object.
|
||||
*
|
||||
* Valid `options`
|
||||
*
|
||||
* db - passed to the connection db instance
|
||||
* server - passed to the connection server instance(s)
|
||||
* replset - passed to the connection ReplSetServer instance
|
||||
* user - username for authentication
|
||||
* pass - password for authentication
|
||||
* auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
|
||||
* mongos - Boolean - if true, enables High Availability support for mongos
|
||||
*
|
||||
* _Options passed take precedence over options included in connection strings._
|
||||
*
|
||||
* ####Notes:
|
||||
*
|
||||
* _If connecting to multiple mongos servers, set the `mongos` option to true._
|
||||
*
|
||||
* conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
|
||||
*
|
||||
* Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
|
||||
* Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
|
||||
* See the node-mongodb-native driver instance for options that it understands.
|
||||
*
|
||||
* _Options passed take precedence over options included in connection strings._
|
||||
*
|
||||
* @param {String} uris comma-separated mongodb:// `URI`s
|
||||
* @param {String} [database] database name if not included in `uris`
|
||||
* @param {Object} [options] passed to the internal driver
|
||||
* @param {Function} [callback]
|
||||
* @see node-mongodb-native https://github.com/mongodb/node-mongodb-native
|
||||
* @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.openSet = function (uris, database, options, callback) {
|
||||
if (!rgxProtocol.test(uris)) {
|
||||
uris = 'mongodb://' + uris;
|
||||
}
|
||||
|
||||
var self = this;
|
||||
|
||||
switch (arguments.length) {
|
||||
case 3:
|
||||
switch (typeof database) {
|
||||
case 'string':
|
||||
this.name = database;
|
||||
break;
|
||||
case 'object':
|
||||
callback = options;
|
||||
options = database;
|
||||
database = null;
|
||||
break;
|
||||
}
|
||||
|
||||
if ('function' === typeof options) {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
switch (typeof database) {
|
||||
case 'string':
|
||||
this.name = database;
|
||||
break;
|
||||
case 'function':
|
||||
callback = database, database = null;
|
||||
break;
|
||||
case 'object':
|
||||
options = database, database = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var parsed;
|
||||
try {
|
||||
parsed = muri(uris);
|
||||
} catch (err) {
|
||||
this.error(err, callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.name = parsed.db;
|
||||
}
|
||||
|
||||
this.hosts = parsed.hosts;
|
||||
this.options = this.parseOptions(options, parsed && parsed.options);
|
||||
this.replica = true;
|
||||
|
||||
if (!this.name) {
|
||||
this.error(new Error('No database name provided for replica set'), callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
// authentication
|
||||
if (options && options.user && options.pass) {
|
||||
this.user = options.user;
|
||||
this.pass = options.pass;
|
||||
|
||||
} else if (parsed && parsed.auth) {
|
||||
this.user = parsed.auth.user;
|
||||
this.pass = parsed.auth.pass;
|
||||
|
||||
} else {
|
||||
this.user = this.pass = undefined;
|
||||
}
|
||||
|
||||
// global configuration options
|
||||
if (options && options.config) {
|
||||
if (options.config.autoIndex === false){
|
||||
this.config.autoIndex = false;
|
||||
}
|
||||
else {
|
||||
this.config.autoIndex = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
this._open(callback);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* error
|
||||
*
|
||||
* Graceful error handling, passes error to callback
|
||||
* if available, else emits error on the connection.
|
||||
*
|
||||
* @param {Error} err
|
||||
* @param {Function} callback optional
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Connection.prototype.error = function (err, callback) {
|
||||
if (callback) return callback(err);
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles opening the connection with the appropriate method based on connection type.
|
||||
*
|
||||
* @param {Function} callback
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Connection.prototype._open = function (callback) {
|
||||
this.readyState = STATES.connecting;
|
||||
this._closeCalled = false;
|
||||
|
||||
var self = this;
|
||||
|
||||
var method = this.replica
|
||||
? 'doOpenSet'
|
||||
: 'doOpen';
|
||||
|
||||
// open connection
|
||||
this[method](function (err) {
|
||||
if (err) {
|
||||
self.readyState = STATES.disconnected;
|
||||
if (self._hasOpened) {
|
||||
if (callback) callback(err);
|
||||
} else {
|
||||
self.error(err, callback);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.onOpen(callback);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the connection is opened
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Connection.prototype.onOpen = function (callback) {
|
||||
var self = this;
|
||||
|
||||
function open(err, isAuth) {
|
||||
if (err) {
|
||||
self.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
|
||||
if (self._hasOpened) {
|
||||
if (callback) callback(err);
|
||||
} else {
|
||||
self.error(err, callback);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.readyState = STATES.connected;
|
||||
|
||||
// avoid having the collection subscribe to our event emitter
|
||||
// to prevent 0.3 warning
|
||||
for (var i in self.collections)
|
||||
self.collections[i].onOpen();
|
||||
|
||||
callback && callback();
|
||||
self.emit('open');
|
||||
};
|
||||
|
||||
// re-authenticate
|
||||
if (self.user && self.pass) {
|
||||
self.db.authenticate(self.user, self.pass, self.options.auth, function(err) {
|
||||
open(err, true);
|
||||
});
|
||||
} else {
|
||||
open();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes the connection
|
||||
*
|
||||
* @param {Function} [callback] optional
|
||||
* @return {Connection} self
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.close = function (callback) {
|
||||
var self = this;
|
||||
this._closeCalled = true;
|
||||
|
||||
switch (this.readyState){
|
||||
case 0: // disconnected
|
||||
callback && callback();
|
||||
break;
|
||||
|
||||
case 1: // connected
|
||||
case 4: // unauthorized
|
||||
this.readyState = STATES.disconnecting;
|
||||
this.doClose(function(err){
|
||||
if (err){
|
||||
self.error(err, callback);
|
||||
} else {
|
||||
self.onClose();
|
||||
callback && callback();
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case 2: // connecting
|
||||
this.once('open', function(){
|
||||
self.close(callback);
|
||||
});
|
||||
break;
|
||||
|
||||
case 3: // disconnecting
|
||||
if (!callback) break;
|
||||
this.once('close', function () {
|
||||
callback();
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Called when the connection closes
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Connection.prototype.onClose = function () {
|
||||
this.readyState = STATES.disconnected;
|
||||
|
||||
// avoid having the collection subscribe to our event emitter
|
||||
// to prevent 0.3 warning
|
||||
for (var i in this.collections)
|
||||
this.collections[i].onClose();
|
||||
|
||||
this.emit('close');
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves a collection, creating it if not cached.
|
||||
*
|
||||
* Not typically needed by applications. Just talk to your collection through your model.
|
||||
*
|
||||
* @param {String} name of the collection
|
||||
* @param {Object} [options] optional collection options
|
||||
* @return {Collection} collection instance
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.collection = function (name, options) {
|
||||
if (!(name in this.collections))
|
||||
this.collections[name] = new Collection(name, this, options);
|
||||
return this.collections[name];
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines or retrieves a model.
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* var db = mongoose.createConnection(..);
|
||||
* db.model('Venue', new Schema(..));
|
||||
* var Ticket = db.model('Ticket', new Schema(..));
|
||||
* var Venue = db.model('Venue');
|
||||
*
|
||||
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var schema = new Schema({ name: String }, { collection: 'actor' });
|
||||
*
|
||||
* // or
|
||||
*
|
||||
* schema.set('collection', 'actor');
|
||||
*
|
||||
* // or
|
||||
*
|
||||
* var collectionName = 'actor'
|
||||
* var M = conn.model('Actor', schema, collectionName)
|
||||
*
|
||||
* @param {String} name the model name
|
||||
* @param {Schema} [schema] a schema. necessary when defining a model
|
||||
* @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
|
||||
* @see Mongoose#model #index_Mongoose-model
|
||||
* @return {Model} The compiled model
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.model = function (name, schema, collection) {
|
||||
// collection name discovery
|
||||
if ('string' == typeof schema) {
|
||||
collection = schema;
|
||||
schema = false;
|
||||
}
|
||||
|
||||
if (utils.isObject(schema) && !(schema instanceof Schema)) {
|
||||
schema = new Schema(schema);
|
||||
}
|
||||
|
||||
if (this.models[name] && !collection) {
|
||||
// model exists but we are not subclassing with custom collection
|
||||
if (schema instanceof Schema && schema != this.models[name].schema) {
|
||||
throw new MongooseError.OverwriteModelError(name);
|
||||
}
|
||||
return this.models[name];
|
||||
}
|
||||
|
||||
var opts = { cache: false, connection: this }
|
||||
var model;
|
||||
|
||||
if (schema instanceof Schema) {
|
||||
// compile a model
|
||||
model = this.base.model(name, schema, collection, opts)
|
||||
|
||||
// only the first model with this name is cached to allow
|
||||
// for one-offs with custom collection names etc.
|
||||
if (!this.models[name]) {
|
||||
this.models[name] = model;
|
||||
}
|
||||
|
||||
model.init();
|
||||
return model;
|
||||
}
|
||||
|
||||
if (this.models[name] && collection) {
|
||||
// subclassing current model with alternate collection
|
||||
model = this.models[name];
|
||||
schema = model.prototype.schema;
|
||||
var sub = model.__subclass(this, schema, collection);
|
||||
// do not cache the sub model
|
||||
return sub;
|
||||
}
|
||||
|
||||
// lookup model in mongoose module
|
||||
model = this.base.models[name];
|
||||
|
||||
if (!model) {
|
||||
throw new MongooseError.MissingSchemaError(name);
|
||||
}
|
||||
|
||||
if (this == model.prototype.db
|
||||
&& (!collection || collection == model.collection.name)) {
|
||||
// model already uses this connection.
|
||||
|
||||
// only the first model with this name is cached to allow
|
||||
// for one-offs with custom collection names etc.
|
||||
if (!this.models[name]) {
|
||||
this.models[name] = model;
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
return this.models[name] = model.__subclass(this, schema, collection);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an array of model names created on this connection.
|
||||
* @api public
|
||||
* @return {Array}
|
||||
*/
|
||||
|
||||
Connection.prototype.modelNames = function () {
|
||||
return Object.keys(this.models);
|
||||
};
|
||||
|
||||
/*!
|
||||
* Noop.
|
||||
*/
|
||||
|
||||
function noop () {}
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
Connection.STATES = STATES;
|
||||
module.exports = Connection;
|
||||
27
node_modules/mongoose/lib/connectionstate.js
generated
vendored
Normal file
27
node_modules/mongoose/lib/connectionstate.js
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
|
||||
/*!
|
||||
* Connection states
|
||||
*/
|
||||
|
||||
var STATES = module.exports = exports = Object.create(null);
|
||||
|
||||
var disconnected = 'disconnected';
|
||||
var connected = 'connected';
|
||||
var connecting = 'connecting';
|
||||
var disconnecting = 'disconnecting';
|
||||
var unauthorized = 'unauthorized';
|
||||
var uninitialized = 'uninitialized';
|
||||
|
||||
STATES[0] = disconnected;
|
||||
STATES[1] = connected;
|
||||
STATES[2] = connecting;
|
||||
STATES[3] = disconnecting;
|
||||
STATES[4] = unauthorized;
|
||||
STATES[99] = uninitialized;
|
||||
|
||||
STATES[disconnected] = 0;
|
||||
STATES[connected] = 1;
|
||||
STATES[connecting] = 2;
|
||||
STATES[disconnecting] = 3;
|
||||
STATES[unauthorized] = 4;
|
||||
STATES[uninitialized] = 99;
|
||||
2138
node_modules/mongoose/lib/document.js
generated
vendored
Normal file
2138
node_modules/mongoose/lib/document.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
20
node_modules/mongoose/lib/document_provider.js
generated
vendored
Normal file
20
node_modules/mongoose/lib/document_provider.js
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
var Document = require('./document.js');
|
||||
var BrowserDocument = require('./browserDocument.js');
|
||||
|
||||
/**
|
||||
* Returns the Document constructor for the current context
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
module.exports = function() {
|
||||
if (typeof window !== 'undefined' && typeof document !== 'undefined' && document === window.document) {
|
||||
return BrowserDocument;
|
||||
} else {
|
||||
return Document;
|
||||
}
|
||||
};
|
||||
4
node_modules/mongoose/lib/drivers/SPEC.md
generated
vendored
Normal file
4
node_modules/mongoose/lib/drivers/SPEC.md
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
|
||||
# Driver Spec
|
||||
|
||||
TODO
|
||||
5
node_modules/mongoose/lib/drivers/browser/ReadPreference.js
generated
vendored
Normal file
5
node_modules/mongoose/lib/drivers/browser/ReadPreference.js
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
module.exports = function() {};
|
||||
12
node_modules/mongoose/lib/drivers/browser/binary.js
generated
vendored
Normal file
12
node_modules/mongoose/lib/drivers/browser/binary.js
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Binary = require('bson').Binary;
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = exports = Binary;
|
||||
7
node_modules/mongoose/lib/drivers/browser/index.js
generated
vendored
Normal file
7
node_modules/mongoose/lib/drivers/browser/index.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
exports.Binary = require('./binary');
|
||||
exports.ObjectId = require('./objectid');
|
||||
exports.ReadPreference = require('./ReadPreference');
|
||||
14
node_modules/mongoose/lib/drivers/browser/objectid.js
generated
vendored
Normal file
14
node_modules/mongoose/lib/drivers/browser/objectid.js
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
/*!
|
||||
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
|
||||
* @constructor NodeMongoDbObjectId
|
||||
* @see ObjectId
|
||||
*/
|
||||
|
||||
var ObjectId = require('bson').ObjectID;
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
module.exports = exports = ObjectId;
|
||||
18
node_modules/mongoose/lib/drivers/index.js
generated
vendored
Normal file
18
node_modules/mongoose/lib/drivers/index.js
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
var driver;
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
driver = require('./' +
|
||||
(global.MONGOOSE_DRIVER_PATH || 'node-mongodb-native'));
|
||||
} else {
|
||||
driver = require('./browser');
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
module.exports = driver;
|
||||
45
node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js
generated
vendored
Normal file
45
node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var mongodb = require('mongodb');
|
||||
var ReadPref = mongodb.ReadPreference;
|
||||
|
||||
/*!
|
||||
* Converts arguments to ReadPrefs the driver
|
||||
* can understand.
|
||||
*
|
||||
* @param {String|Array} pref
|
||||
* @param {Array} [tags]
|
||||
*/
|
||||
|
||||
module.exports = function readPref (pref, tags) {
|
||||
if (Array.isArray(pref)) {
|
||||
tags = pref[1];
|
||||
pref = pref[0];
|
||||
}
|
||||
|
||||
if (pref instanceof ReadPref) {
|
||||
return pref;
|
||||
}
|
||||
|
||||
switch (pref) {
|
||||
case 'p':
|
||||
pref = 'primary';
|
||||
break;
|
||||
case 'pp':
|
||||
pref = 'primaryPreferred';
|
||||
break;
|
||||
case 's':
|
||||
pref = 'secondary';
|
||||
break;
|
||||
case 'sp':
|
||||
pref = 'secondaryPreferred';
|
||||
break;
|
||||
case 'n':
|
||||
pref = 'nearest';
|
||||
break;
|
||||
}
|
||||
|
||||
return new ReadPref(pref, tags);
|
||||
}
|
||||
8
node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
generated
vendored
Normal file
8
node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Binary = require('mongodb').Binary;
|
||||
|
||||
module.exports = exports = Binary;
|
||||
225
node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js
generated
vendored
Normal file
225
node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js
generated
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseCollection = require('../../collection')
|
||||
, Collection = require('mongodb').Collection
|
||||
, STATES = require('../../connectionstate')
|
||||
, utils = require('../../utils')
|
||||
|
||||
/**
|
||||
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation.
|
||||
*
|
||||
* All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management.
|
||||
*
|
||||
* @inherits Collection
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function NativeCollection () {
|
||||
this.collection = null;
|
||||
MongooseCollection.apply(this, arguments);
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherit from abstract Collection.
|
||||
*/
|
||||
|
||||
NativeCollection.prototype.__proto__ = MongooseCollection.prototype;
|
||||
|
||||
/**
|
||||
* Called when the connection opens.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NativeCollection.prototype.onOpen = function () {
|
||||
var self = this;
|
||||
|
||||
// always get a new collection in case the user changed host:port
|
||||
// of parent db instance when re-opening the connection.
|
||||
|
||||
if (!self.opts.capped.size) {
|
||||
// non-capped
|
||||
return self.conn.db.collection(self.name, callback);
|
||||
}
|
||||
|
||||
// capped
|
||||
return self.conn.db.collection(self.name, function (err, c) {
|
||||
if (err) return callback(err);
|
||||
|
||||
// discover if this collection exists and if it is capped
|
||||
self.conn.db.listCollections({ name: self.name }).toArray(function(err, docs) {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
var doc = docs[0];
|
||||
var exists = !!doc;
|
||||
|
||||
if (exists) {
|
||||
if (doc.options && doc.options.capped) {
|
||||
callback(null, c);
|
||||
} else {
|
||||
var msg = 'A non-capped collection exists with the name: '+ self.name +'\n\n'
|
||||
+ ' To use this collection as a capped collection, please '
|
||||
+ 'first convert it.\n'
|
||||
+ ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'
|
||||
err = new Error(msg);
|
||||
callback(err);
|
||||
}
|
||||
} else {
|
||||
// create
|
||||
var opts = utils.clone(self.opts.capped);
|
||||
opts.capped = true;
|
||||
self.conn.db.createCollection(self.name, opts, callback);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function callback (err, collection) {
|
||||
if (err) {
|
||||
// likely a strict mode error
|
||||
self.conn.emit('error', err);
|
||||
} else {
|
||||
self.collection = collection;
|
||||
MongooseCollection.prototype.onOpen.call(self);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Called when the connection closes
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NativeCollection.prototype.onClose = function () {
|
||||
MongooseCollection.prototype.onClose.call(this);
|
||||
};
|
||||
|
||||
/*!
|
||||
* Copy the collection methods and make them subject to queues
|
||||
*/
|
||||
|
||||
for (var i in Collection.prototype) {
|
||||
// Janky hack to work around gh-3005 until we can get rid of the mongoose
|
||||
// collection abstraction
|
||||
try {
|
||||
if (typeof Collection.prototype[i] !== 'function') {
|
||||
continue;
|
||||
}
|
||||
} catch(e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
(function(i){
|
||||
NativeCollection.prototype[i] = function () {
|
||||
if (this.buffer) {
|
||||
this.addQueue(i, arguments);
|
||||
return;
|
||||
}
|
||||
|
||||
var collection = this.collection
|
||||
, args = arguments
|
||||
, self = this
|
||||
, debug = self.conn.base.options.debug;
|
||||
|
||||
if (debug) {
|
||||
if ('function' === typeof debug) {
|
||||
debug.apply(debug
|
||||
, [self.name, i].concat(utils.args(args, 0, args.length-1)));
|
||||
} else {
|
||||
console.error('\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s'
|
||||
, self.name
|
||||
, i
|
||||
, print(args[0])
|
||||
, print(args[1])
|
||||
, print(args[2])
|
||||
, print(args[3]))
|
||||
}
|
||||
}
|
||||
|
||||
return collection[i].apply(collection, args);
|
||||
};
|
||||
})(i);
|
||||
}
|
||||
|
||||
/*!
|
||||
* Debug print helper
|
||||
*/
|
||||
|
||||
function print (arg) {
|
||||
var type = typeof arg;
|
||||
if ('function' === type || 'undefined' === type) return '';
|
||||
return format(arg);
|
||||
}
|
||||
|
||||
/*!
|
||||
* Debug print helper
|
||||
*/
|
||||
|
||||
function format (obj, sub) {
|
||||
var x = utils.clone(obj, { retainKeyOrder: 1 });
|
||||
if (x) {
|
||||
if ('Binary' === x.constructor.name) {
|
||||
x = '[object Buffer]';
|
||||
} else if ('ObjectID' === x.constructor.name) {
|
||||
var representation = 'ObjectId("' + x.toHexString() + '")';
|
||||
x = { inspect: function() { return representation; } };
|
||||
} else if ('Date' === x.constructor.name) {
|
||||
var representation = 'new Date("' + x.toUTCString() + '")';
|
||||
x = { inspect: function() { return representation; } };
|
||||
} else if ('Object' === x.constructor.name) {
|
||||
var keys = Object.keys(x);
|
||||
var numKeys = keys.length;
|
||||
var key;
|
||||
for (var i = 0; i < numKeys; ++i) {
|
||||
key = keys[i];
|
||||
if (x[key]) {
|
||||
if ('Binary' === x[key].constructor.name) {
|
||||
x[key] = '[object Buffer]';
|
||||
} else if ('Object' === x[key].constructor.name) {
|
||||
x[key] = format(x[key], true);
|
||||
} else if ('ObjectID' === x[key].constructor.name) {
|
||||
;(function(x){
|
||||
var representation = 'ObjectId("' + x[key].toHexString() + '")';
|
||||
x[key] = { inspect: function() { return representation; } };
|
||||
})(x)
|
||||
} else if ('Date' === x[key].constructor.name) {
|
||||
;(function(x){
|
||||
var representation = 'new Date("' + x[key].toUTCString() + '")';
|
||||
x[key] = { inspect: function() { return representation; } };
|
||||
})(x)
|
||||
} else if (Array.isArray(x[key])) {
|
||||
x[key] = x[key].map(function (o) {
|
||||
return format(o, true)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sub) return x;
|
||||
}
|
||||
|
||||
return require('util')
|
||||
.inspect(x, false, 10, true)
|
||||
.replace(/\n/g, '')
|
||||
.replace(/\s{2,}/g, ' ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Retreives information about this collections indexes.
|
||||
*
|
||||
* @param {Function} callback
|
||||
* @method getIndexes
|
||||
* @api public
|
||||
*/
|
||||
|
||||
NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation;
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = NativeCollection;
|
||||
378
node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js
generated
vendored
Normal file
378
node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js
generated
vendored
Normal file
@@ -0,0 +1,378 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseConnection = require('../../connection')
|
||||
, mongo = require('mongodb')
|
||||
, Db = mongo.Db
|
||||
, Server = mongo.Server
|
||||
, Mongos = mongo.Mongos
|
||||
, STATES = require('../../connectionstate')
|
||||
, ReplSetServers = mongo.ReplSet
|
||||
, utils = require('../../utils');
|
||||
|
||||
/**
|
||||
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
|
||||
*
|
||||
* @inherits Connection
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function NativeConnection() {
|
||||
MongooseConnection.apply(this, arguments);
|
||||
this._listening = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose the possible connection states.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
NativeConnection.STATES = STATES;
|
||||
|
||||
/*!
|
||||
* Inherits from Connection.
|
||||
*/
|
||||
|
||||
NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
|
||||
|
||||
/**
|
||||
* Opens the connection to MongoDB.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Connection} this
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NativeConnection.prototype.doOpen = function (fn) {
|
||||
if (this.db) {
|
||||
mute(this);
|
||||
}
|
||||
|
||||
var server = new Server(this.host, this.port, this.options.server);
|
||||
this.db = new Db(this.name, server, this.options.db);
|
||||
|
||||
var self = this;
|
||||
this.db.open(function (err) {
|
||||
if (err) return fn(err);
|
||||
listen(self);
|
||||
fn();
|
||||
});
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Switches to a different database using the same connection pool.
|
||||
*
|
||||
* Returns a new connection object, with the new db.
|
||||
*
|
||||
* @param {String} name The database name
|
||||
* @return {Connection} New Connection Object
|
||||
* @api public
|
||||
*/
|
||||
|
||||
NativeConnection.prototype.useDb = function (name) {
|
||||
// we have to manually copy all of the attributes...
|
||||
var newConn = new this.constructor();
|
||||
newConn.name = name;
|
||||
newConn.base = this.base;
|
||||
newConn.collections = {};
|
||||
newConn.models = {};
|
||||
newConn.replica = this.replica;
|
||||
newConn.hosts = this.hosts;
|
||||
newConn.host = this.host;
|
||||
newConn.port = this.port;
|
||||
newConn.user = this.user;
|
||||
newConn.pass = this.pass;
|
||||
newConn.options = this.options;
|
||||
newConn._readyState = this._readyState;
|
||||
newConn._closeCalled = this._closeCalled;
|
||||
newConn._hasOpened = this._hasOpened;
|
||||
newConn._listening = false;
|
||||
|
||||
// First, when we create another db object, we are not guaranteed to have a
|
||||
// db object to work with. So, in the case where we have a db object and it
|
||||
// is connected, we can just proceed with setting everything up. However, if
|
||||
// we do not have a db or the state is not connected, then we need to wait on
|
||||
// the 'open' event of the connection before doing the rest of the setup
|
||||
// the 'connected' event is the first time we'll have access to the db object
|
||||
|
||||
var self = this;
|
||||
|
||||
if (this.db && this._readyState === STATES.connected) {
|
||||
wireup();
|
||||
} else {
|
||||
this.once('connected', wireup);
|
||||
}
|
||||
|
||||
function wireup () {
|
||||
newConn.db = self.db.db(name);
|
||||
newConn.onOpen();
|
||||
// setup the events appropriately
|
||||
listen(newConn);
|
||||
}
|
||||
|
||||
newConn.name = name;
|
||||
|
||||
// push onto the otherDbs stack, this is used when state changes
|
||||
this.otherDbs.push(newConn);
|
||||
newConn.otherDbs.push(this);
|
||||
|
||||
return newConn;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Register listeners for important events and bubble appropriately.
|
||||
*/
|
||||
|
||||
function listen (conn) {
|
||||
if (conn._listening) return;
|
||||
conn._listening = true;
|
||||
|
||||
conn.db.on('close', function(){
|
||||
if (conn._closeCalled) return;
|
||||
|
||||
// the driver never emits an `open` event. auto_reconnect still
|
||||
// emits a `close` event but since we never get another
|
||||
// `open` we can't emit close
|
||||
if (conn.db.serverConfig.autoReconnect) {
|
||||
conn.readyState = STATES.disconnected;
|
||||
conn.emit('close');
|
||||
return;
|
||||
}
|
||||
conn.onClose();
|
||||
});
|
||||
conn.db.on('error', function(err){
|
||||
conn.emit('error', err);
|
||||
});
|
||||
conn.db.on('reconnect', function() {
|
||||
conn.readyState = STATES.connected;
|
||||
conn.emit('reconnected');
|
||||
});
|
||||
conn.db.on('timeout', function(err){
|
||||
var error = new Error(err && err.err || 'connection timeout');
|
||||
conn.emit('error', error);
|
||||
});
|
||||
conn.db.on('open', function (err, db) {
|
||||
if (STATES.disconnected === conn.readyState && db && db.databaseName) {
|
||||
conn.readyState = STATES.connected;
|
||||
conn.emit('reconnected');
|
||||
}
|
||||
});
|
||||
conn.db.on('parseError', function(err) {
|
||||
conn.emit('parseError', err);
|
||||
});
|
||||
}
|
||||
|
||||
/*!
|
||||
* Remove listeners registered in `listen`
|
||||
*/
|
||||
|
||||
function mute (conn) {
|
||||
if (!conn.db) throw new Error('missing db');
|
||||
conn.db.removeAllListeners("close");
|
||||
conn.db.removeAllListeners("error");
|
||||
conn.db.removeAllListeners("timeout");
|
||||
conn.db.removeAllListeners("open");
|
||||
conn.db.removeAllListeners("fullsetup");
|
||||
conn._listening = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a connection to a MongoDB ReplicaSet.
|
||||
*
|
||||
* See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
* @return {Connection} this
|
||||
*/
|
||||
|
||||
NativeConnection.prototype.doOpenSet = function (fn) {
|
||||
if (this.db) {
|
||||
mute(this);
|
||||
}
|
||||
|
||||
var servers = []
|
||||
, self = this;
|
||||
|
||||
this.hosts.forEach(function (server) {
|
||||
var host = server.host || server.ipc;
|
||||
var port = server.port || 27017;
|
||||
servers.push(new Server(host, port, self.options.server));
|
||||
})
|
||||
|
||||
var server = this.options.mongos
|
||||
? new Mongos(servers, this.options.mongos)
|
||||
: new ReplSetServers(servers, this.options.replset);
|
||||
this.db = new Db(this.name, server, this.options.db);
|
||||
|
||||
this.db.on('fullsetup', function () {
|
||||
self.emit('fullsetup')
|
||||
});
|
||||
|
||||
this.db.open(function (err) {
|
||||
if (err) return fn(err);
|
||||
fn();
|
||||
listen(self);
|
||||
});
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes the connection
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Connection} this
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NativeConnection.prototype.doClose = function (fn) {
|
||||
this.db.close();
|
||||
if (fn) fn();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares default connection options for the node-mongodb-native driver.
|
||||
*
|
||||
* _NOTE: `passed` options take precedence over connection string options._
|
||||
*
|
||||
* @param {Object} passed options that were passed directly during connection
|
||||
* @param {Object} [connStrOptions] options that were passed in the connection string
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
|
||||
var o = passed || {};
|
||||
o.db || (o.db = {});
|
||||
o.auth || (o.auth = {});
|
||||
o.server || (o.server = {});
|
||||
o.replset || (o.replset = {});
|
||||
o.server.socketOptions || (o.server.socketOptions = {});
|
||||
o.replset.socketOptions || (o.replset.socketOptions = {});
|
||||
|
||||
var opts = connStrOpts || {};
|
||||
Object.keys(opts).forEach(function (name) {
|
||||
switch (name) {
|
||||
case 'ssl':
|
||||
case 'poolSize':
|
||||
if ('undefined' == typeof o.server[name]) {
|
||||
o.server[name] = o.replset[name] = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'slaveOk':
|
||||
if ('undefined' == typeof o.server.slave_ok) {
|
||||
o.server.slave_ok = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'autoReconnect':
|
||||
if ('undefined' == typeof o.server.auto_reconnect) {
|
||||
o.server.auto_reconnect = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'socketTimeoutMS':
|
||||
case 'connectTimeoutMS':
|
||||
if ('undefined' == typeof o.server.socketOptions[name]) {
|
||||
o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'authdb':
|
||||
if ('undefined' == typeof o.auth.authdb) {
|
||||
o.auth.authdb = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'authSource':
|
||||
if ('undefined' == typeof o.auth.authSource) {
|
||||
o.auth.authSource = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'retries':
|
||||
case 'reconnectWait':
|
||||
case 'rs_name':
|
||||
if ('undefined' == typeof o.replset[name]) {
|
||||
o.replset[name] = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'replicaSet':
|
||||
if ('undefined' == typeof o.replset.rs_name) {
|
||||
o.replset.rs_name = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'readSecondary':
|
||||
if ('undefined' == typeof o.replset.read_secondary) {
|
||||
o.replset.read_secondary = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'nativeParser':
|
||||
if ('undefined' == typeof o.db.native_parser) {
|
||||
o.db.native_parser = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'w':
|
||||
case 'safe':
|
||||
case 'fsync':
|
||||
case 'journal':
|
||||
case 'wtimeoutMS':
|
||||
if ('undefined' == typeof o.db[name]) {
|
||||
o.db[name] = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'readPreference':
|
||||
if ('undefined' == typeof o.db.read_preference) {
|
||||
o.db.read_preference = opts[name];
|
||||
}
|
||||
break;
|
||||
case 'readPreferenceTags':
|
||||
if ('undefined' == typeof o.db.read_preference_tags) {
|
||||
o.db.read_preference_tags = opts[name];
|
||||
}
|
||||
break;
|
||||
}
|
||||
})
|
||||
|
||||
if (!('auto_reconnect' in o.server)) {
|
||||
o.server.auto_reconnect = true;
|
||||
}
|
||||
|
||||
if (!o.db.read_preference) {
|
||||
// read from primaries by default
|
||||
o.db.read_preference = 'primary';
|
||||
}
|
||||
|
||||
// mongoose creates its own ObjectIds
|
||||
o.db.forceServerObjectId = false;
|
||||
|
||||
// default safe using new nomenclature
|
||||
if (!('journal' in o.db || 'j' in o.db ||
|
||||
'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) {
|
||||
o.db.w = 1;
|
||||
}
|
||||
|
||||
validate(o);
|
||||
return o;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Validates the driver db options.
|
||||
*
|
||||
* @param {Object} o
|
||||
*/
|
||||
|
||||
function validate (o) {
|
||||
if (-1 === o.db.w || 0 === o.db.w) {
|
||||
if (o.db.journal || o.db.fsync || o.db.safe) {
|
||||
throw new Error(
|
||||
'Invalid writeConcern: '
|
||||
+ 'w set to -1 or 0 cannot be combined with safe|fsync|journal');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = NativeConnection;
|
||||
7
node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
generated
vendored
Normal file
7
node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
exports.Binary = require('./binary');
|
||||
exports.ObjectId = require('./objectid');
|
||||
exports.ReadPreference = require('./ReadPreference');
|
||||
14
node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js
generated
vendored
Normal file
14
node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
/*!
|
||||
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
|
||||
* @constructor NodeMongoDbObjectId
|
||||
* @see ObjectId
|
||||
*/
|
||||
|
||||
var ObjectId = require('mongodb').ObjectId;
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
module.exports = exports = ObjectId;
|
||||
51
node_modules/mongoose/lib/error.js
generated
vendored
Normal file
51
node_modules/mongoose/lib/error.js
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
|
||||
/**
|
||||
* MongooseError constructor
|
||||
*
|
||||
* @param {String} msg Error message
|
||||
* @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
|
||||
*/
|
||||
|
||||
function MongooseError (msg) {
|
||||
Error.call(this);
|
||||
this.stack = new Error().stack;
|
||||
this.message = msg;
|
||||
this.name = 'MongooseError';
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherits from Error.
|
||||
*/
|
||||
|
||||
MongooseError.prototype = Object.create(Error.prototype);
|
||||
MongooseError.prototype.constructor = Error;
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = exports = MongooseError;
|
||||
|
||||
/**
|
||||
* The default built-in validator error messages.
|
||||
*
|
||||
* @see Error.messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
MongooseError.messages = require('./error/messages');
|
||||
|
||||
// backward compat
|
||||
MongooseError.Messages = MongooseError.messages;
|
||||
|
||||
/*!
|
||||
* Expose subclasses
|
||||
*/
|
||||
|
||||
MongooseError.CastError = require('./error/cast');
|
||||
MongooseError.ValidationError = require('./error/validation')
|
||||
MongooseError.ValidatorError = require('./error/validator')
|
||||
MongooseError.VersionError =require('./error/version')
|
||||
MongooseError.OverwriteModelError = require('./error/overwriteModel')
|
||||
MongooseError.MissingSchemaError = require('./error/missingSchema')
|
||||
MongooseError.DivergentArrayError = require('./error/divergentArray')
|
||||
33
node_modules/mongoose/lib/error/browserMissingSchema.js
generated
vendored
Normal file
33
node_modules/mongoose/lib/error/browserMissingSchema.js
generated
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/*!
|
||||
* MissingSchema Error constructor.
|
||||
*
|
||||
* @inherits MongooseError
|
||||
*/
|
||||
|
||||
function MissingSchemaError (name) {
|
||||
var msg = 'Schema hasn\'t been registered for document.\n'
|
||||
+ 'Use mongoose.Document(name, schema)';
|
||||
MongooseError.call(this, msg);
|
||||
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'MissingSchemaError';
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
|
||||
MissingSchemaError.prototype.constructor = MongooseError;
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = MissingSchemaError;
|
||||
37
node_modules/mongoose/lib/error/cast.js
generated
vendored
Normal file
37
node_modules/mongoose/lib/error/cast.js
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/**
|
||||
* Casting Error constructor.
|
||||
*
|
||||
* @param {String} type
|
||||
* @param {String} value
|
||||
* @inherits MongooseError
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function CastError (type, value, path) {
|
||||
MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"');
|
||||
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'CastError';
|
||||
this.kind = type;
|
||||
this.value = value;
|
||||
this.path = path;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
CastError.prototype = Object.create(MongooseError.prototype);
|
||||
CastError.prototype.constructor = MongooseError;
|
||||
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = CastError;
|
||||
42
node_modules/mongoose/lib/error/divergentArray.js
generated
vendored
Normal file
42
node_modules/mongoose/lib/error/divergentArray.js
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/*!
|
||||
* DivergentArrayError constructor.
|
||||
*
|
||||
* @inherits MongooseError
|
||||
*/
|
||||
|
||||
function DivergentArrayError (paths) {
|
||||
var msg = 'For your own good, using `document.save()` to update an array '
|
||||
+ 'which was selected using an $elemMatch projection OR '
|
||||
+ 'populated using skip, limit, query conditions, or exclusion of '
|
||||
+ 'the _id field when the operation results in a $pop or $set of '
|
||||
+ 'the entire array is not supported. The following '
|
||||
+ 'path(s) would have been modified unsafely:\n'
|
||||
+ ' ' + paths.join('\n ') + '\n'
|
||||
+ 'Use Model.update() to update these arrays instead.'
|
||||
// TODO write up a docs page (FAQ) and link to it
|
||||
|
||||
MongooseError.call(this, msg);
|
||||
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'DivergentArrayError';
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
DivergentArrayError.prototype = Object.create(MongooseError.prototype);
|
||||
DivergentArrayError.prototype.constructor = MongooseError;
|
||||
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = DivergentArrayError;
|
||||
43
node_modules/mongoose/lib/error/messages.js
generated
vendored
Normal file
43
node_modules/mongoose/lib/error/messages.js
generated
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
/**
|
||||
* The default built-in validator error messages. These may be customized.
|
||||
*
|
||||
* // customize within each schema or globally like so
|
||||
* var mongoose = require('mongoose');
|
||||
* mongoose.Error.messages.String.enum = "Your custom message for {PATH}.";
|
||||
*
|
||||
* As you might have noticed, error messages support basic templating
|
||||
*
|
||||
* - `{PATH}` is replaced with the invalid document path
|
||||
* - `{VALUE}` is replaced with the invalid value
|
||||
* - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined"
|
||||
* - `{MIN}` is replaced with the declared min value for the Number.min validator
|
||||
* - `{MAX}` is replaced with the declared max value for the Number.max validator
|
||||
*
|
||||
* Click the "show code" link below to see all defaults.
|
||||
*
|
||||
* @property messages
|
||||
* @receiver MongooseError
|
||||
* @api public
|
||||
*/
|
||||
|
||||
var msg = module.exports = exports = {};
|
||||
|
||||
msg.general = {};
|
||||
msg.general.default = "Validator failed for path `{PATH}` with value `{VALUE}`";
|
||||
msg.general.required = "Path `{PATH}` is required.";
|
||||
|
||||
msg.Number = {};
|
||||
msg.Number.min = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).";
|
||||
msg.Number.max = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).";
|
||||
|
||||
msg.Date = {};
|
||||
msg.Date.min = "Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).";
|
||||
msg.Date.max = "Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).";
|
||||
|
||||
msg.String = {};
|
||||
msg.String.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`.";
|
||||
msg.String.match = "Path `{PATH}` is invalid ({VALUE}).";
|
||||
msg.String.minlength = "Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).";
|
||||
msg.String.maxlength = "Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).";
|
||||
|
||||
33
node_modules/mongoose/lib/error/missingSchema.js
generated
vendored
Normal file
33
node_modules/mongoose/lib/error/missingSchema.js
generated
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/*!
|
||||
* MissingSchema Error constructor.
|
||||
*
|
||||
* @inherits MongooseError
|
||||
*/
|
||||
|
||||
function MissingSchemaError (name) {
|
||||
var msg = 'Schema hasn\'t been registered for model "' + name + '".\n'
|
||||
+ 'Use mongoose.model(name, schema)';
|
||||
MongooseError.call(this, msg);
|
||||
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'MissingSchemaError';
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
|
||||
MissingSchemaError.prototype.constructor = MongooseError;
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = MissingSchemaError;
|
||||
31
node_modules/mongoose/lib/error/overwriteModel.js
generated
vendored
Normal file
31
node_modules/mongoose/lib/error/overwriteModel.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/*!
|
||||
* OverwriteModel Error constructor.
|
||||
*
|
||||
* @inherits MongooseError
|
||||
*/
|
||||
|
||||
function OverwriteModelError (name) {
|
||||
MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.');
|
||||
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'OverwriteModelError';
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
OverwriteModelError.prototype = Object.create(MongooseError.prototype);
|
||||
OverwriteModelError.prototype.constructor = MongooseError;
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = OverwriteModelError;
|
||||
58
node_modules/mongoose/lib/error/validation.js
generated
vendored
Normal file
58
node_modules/mongoose/lib/error/validation.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
|
||||
/*!
|
||||
* Module requirements
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/**
|
||||
* Document Validation Error
|
||||
*
|
||||
* @api private
|
||||
* @param {Document} instance
|
||||
* @inherits MongooseError
|
||||
*/
|
||||
|
||||
function ValidationError (instance) {
|
||||
if (instance && instance.constructor.name === 'model') {
|
||||
MongooseError.call(this, instance.constructor.modelName + " validation failed");
|
||||
} else {
|
||||
MongooseError.call(this, "Validation failed");
|
||||
}
|
||||
this.stack = new Error().stack;
|
||||
this.name = 'ValidationError';
|
||||
this.errors = {};
|
||||
if (instance) {
|
||||
instance.errors = this.errors;
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
ValidationError.prototype = Object.create(MongooseError.prototype);
|
||||
ValidationError.prototype.constructor = MongooseError;
|
||||
|
||||
|
||||
/**
|
||||
* Console.log helper
|
||||
*/
|
||||
|
||||
ValidationError.prototype.toString = function () {
|
||||
var ret = this.name + ': ';
|
||||
var msgs = [];
|
||||
|
||||
Object.keys(this.errors).forEach(function (key) {
|
||||
if (this == this.errors[key]) return;
|
||||
msgs.push(String(this.errors[key]));
|
||||
}, this);
|
||||
|
||||
return ret + msgs.join(', ');
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports
|
||||
*/
|
||||
|
||||
module.exports = exports = ValidationError;
|
||||
67
node_modules/mongoose/lib/error/validator.js
generated
vendored
Normal file
67
node_modules/mongoose/lib/error/validator.js
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
var errorMessages = MongooseError.messages;
|
||||
|
||||
/**
|
||||
* Schema validator error
|
||||
*
|
||||
* @param {Object} properties
|
||||
* @inherits MongooseError
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function ValidatorError (properties) {
|
||||
var msg = properties.message;
|
||||
if (!msg) {
|
||||
msg = errorMessages.general.default;
|
||||
}
|
||||
|
||||
this.properties = properties;
|
||||
var message = this.formatMessage(msg, properties);
|
||||
MongooseError.call(this, message);
|
||||
this.stack = new Error().stack;
|
||||
this.name = 'ValidatorError';
|
||||
this.kind = properties.type;
|
||||
this.path = properties.path;
|
||||
this.value = properties.value;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError
|
||||
*/
|
||||
|
||||
ValidatorError.prototype = Object.create(MongooseError.prototype);
|
||||
ValidatorError.prototype.constructor = MongooseError;
|
||||
|
||||
/*!
|
||||
* Formats error messages
|
||||
*/
|
||||
|
||||
ValidatorError.prototype.formatMessage = function (msg, properties) {
|
||||
var propertyNames = Object.keys(properties);
|
||||
for (var i = 0; i < propertyNames.length; ++i) {
|
||||
var propertyName = propertyNames[i];
|
||||
if (propertyName === 'message') {
|
||||
continue;
|
||||
}
|
||||
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
|
||||
}
|
||||
return msg;
|
||||
};
|
||||
|
||||
/*!
|
||||
* toString helper
|
||||
*/
|
||||
|
||||
ValidatorError.prototype.toString = function () {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = ValidatorError;
|
||||
32
node_modules/mongoose/lib/error/version.js
generated
vendored
Normal file
32
node_modules/mongoose/lib/error/version.js
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var MongooseError = require('../error.js');
|
||||
|
||||
/**
|
||||
* Version Error constructor.
|
||||
*
|
||||
* @inherits MongooseError
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function VersionError () {
|
||||
MongooseError.call(this, 'No matching document found.');
|
||||
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'VersionError';
|
||||
};
|
||||
|
||||
/*!
|
||||
* Inherits from MongooseError.
|
||||
*/
|
||||
|
||||
VersionError.prototype = Object.create(MongooseError.prototype);
|
||||
VersionError.prototype.constructor = MongooseError;
|
||||
|
||||
/*!
|
||||
* exports
|
||||
*/
|
||||
|
||||
module.exports = VersionError;
|
||||
655
node_modules/mongoose/lib/index.js
generated
vendored
Normal file
655
node_modules/mongoose/lib/index.js
generated
vendored
Normal file
@@ -0,0 +1,655 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Schema = require('./schema')
|
||||
, SchemaType = require('./schematype')
|
||||
, VirtualType = require('./virtualtype')
|
||||
, STATES = require('./connectionstate')
|
||||
, Types = require('./types')
|
||||
, Query = require('./query')
|
||||
, Promise = require('./promise')
|
||||
, Model = require('./model')
|
||||
, Document = require('./document')
|
||||
, utils = require('./utils')
|
||||
, format = utils.toCollectionName
|
||||
, mongodb = require('mongodb')
|
||||
, pkg = require('../package.json')
|
||||
|
||||
var querystring = require('querystring');
|
||||
|
||||
/**
|
||||
* Mongoose constructor.
|
||||
*
|
||||
* The exports object of the `mongoose` module is an instance of this class.
|
||||
* Most apps will only use this one instance.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Mongoose () {
|
||||
this.connections = [];
|
||||
this.plugins = [];
|
||||
this.models = {};
|
||||
this.modelSchemas = {};
|
||||
// default global options
|
||||
this.options = {
|
||||
pluralization: true
|
||||
};
|
||||
var conn = this.createConnection(); // default connection
|
||||
conn.models = this.models;
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose connection states for user-land
|
||||
*
|
||||
*/
|
||||
Mongoose.prototype.STATES = STATES;
|
||||
|
||||
/**
|
||||
* Sets mongoose options
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* mongoose.set('test', value) // sets the 'test' option to `value`
|
||||
*
|
||||
* mongoose.set('debug', true) // enable logging collection methods + arguments to the console
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {String} value
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.set = function (key, value) {
|
||||
if (arguments.length == 1) {
|
||||
return this.options[key];
|
||||
}
|
||||
|
||||
this.options[key] = value;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets mongoose options
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* mongoose.get('test') // returns the 'test' value
|
||||
*
|
||||
* @param {String} key
|
||||
* @method get
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.get = Mongoose.prototype.set;
|
||||
|
||||
/*!
|
||||
* ReplSet connection string check.
|
||||
*/
|
||||
|
||||
var rgxReplSet = /^.+,.+$/;
|
||||
|
||||
/**
|
||||
* Checks if ?replicaSet query parameter is specified in URI
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* checkReplicaSetInUri('localhost:27000?replicaSet=rs0'); // true
|
||||
*
|
||||
* @param {String} uri
|
||||
* @return {boolean}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
var checkReplicaSetInUri = function(uri) {
|
||||
if (!uri) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var queryStringStart = uri.indexOf('?');
|
||||
var isReplicaSet = false;
|
||||
if (queryStringStart !== -1) {
|
||||
try {
|
||||
var obj = querystring.parse(uri.substr(queryStringStart + 1));
|
||||
if (obj && obj.replicaSet) {
|
||||
isReplicaSet = true;
|
||||
}
|
||||
} catch(e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return isReplicaSet;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a Connection instance.
|
||||
*
|
||||
* Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections.
|
||||
*
|
||||
* If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._
|
||||
*
|
||||
* _Options passed take precedence over options included in connection strings._
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* // with mongodb:// URI
|
||||
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
|
||||
*
|
||||
* // and options
|
||||
* var opts = { db: { native_parser: true }}
|
||||
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
|
||||
*
|
||||
* // replica sets
|
||||
* db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
|
||||
*
|
||||
* // and options
|
||||
* var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
|
||||
* db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
|
||||
*
|
||||
* // with [host, database_name[, port] signature
|
||||
* db = mongoose.createConnection('localhost', 'database', port)
|
||||
*
|
||||
* // and options
|
||||
* var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
|
||||
* db = mongoose.createConnection('localhost', 'database', port, opts)
|
||||
*
|
||||
* // initialize now, connect later
|
||||
* db = mongoose.createConnection();
|
||||
* db.open('localhost', 'database', port, [opts]);
|
||||
*
|
||||
* @param {String} [uri] a mongodb:// URI
|
||||
* @param {Object} [options] options to pass to the driver
|
||||
* @see Connection#open #connection_Connection-open
|
||||
* @see Connection#openSet #connection_Connection-openSet
|
||||
* @return {Connection} the created Connection object
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.createConnection = function () {
|
||||
var conn = new Connection(this);
|
||||
this.connections.push(conn);
|
||||
|
||||
if (arguments.length) {
|
||||
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
|
||||
conn.openSet.apply(conn, arguments);
|
||||
} else {
|
||||
conn.open.apply(conn, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
return conn;
|
||||
};
|
||||
|
||||
/**
|
||||
* Opens the default mongoose connection.
|
||||
*
|
||||
* If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately.
|
||||
*
|
||||
* _Options passed take precedence over options included in connection strings._
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* mongoose.connect('mongodb://user:pass@localhost:port/database');
|
||||
*
|
||||
* // replica sets
|
||||
* var uri = 'mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port';
|
||||
* mongoose.connect(uri);
|
||||
*
|
||||
* // with options
|
||||
* mongoose.connect(uri, options);
|
||||
*
|
||||
* // connecting to multiple mongos
|
||||
* var uri = 'mongodb://hostA:27501,hostB:27501';
|
||||
* var opts = { mongos: true };
|
||||
* mongoose.connect(uri, opts);
|
||||
*
|
||||
* @param {String} uri(s)
|
||||
* @param {Object} [options]
|
||||
* @param {Function} [callback]
|
||||
* @see Mongoose#createConnection #index_Mongoose-createConnection
|
||||
* @api public
|
||||
* @return {Mongoose} this
|
||||
*/
|
||||
|
||||
Mongoose.prototype.connect = function() {
|
||||
var conn = this.connection;
|
||||
|
||||
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
|
||||
conn.openSet.apply(conn, arguments);
|
||||
} else {
|
||||
conn.open.apply(conn, arguments);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Disconnects all connections.
|
||||
*
|
||||
* @param {Function} [fn] called after all connection close.
|
||||
* @return {Mongoose} this
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.disconnect = function (fn) {
|
||||
var count = this.connections.length
|
||||
, error
|
||||
|
||||
this.connections.forEach(function(conn){
|
||||
conn.close(function(err){
|
||||
if (error) return;
|
||||
|
||||
if (err) {
|
||||
error = err;
|
||||
if (fn) return fn(err);
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (fn)
|
||||
--count || fn();
|
||||
});
|
||||
});
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines a model or retrieves it.
|
||||
*
|
||||
* Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
*
|
||||
* // define an Actor model with this mongoose instance
|
||||
* mongoose.model('Actor', new Schema({ name: String }));
|
||||
*
|
||||
* // create a new connection
|
||||
* var conn = mongoose.createConnection(..);
|
||||
*
|
||||
* // retrieve the Actor model
|
||||
* var Actor = conn.model('Actor');
|
||||
*
|
||||
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var schema = new Schema({ name: String }, { collection: 'actor' });
|
||||
*
|
||||
* // or
|
||||
*
|
||||
* schema.set('collection', 'actor');
|
||||
*
|
||||
* // or
|
||||
*
|
||||
* var collectionName = 'actor'
|
||||
* var M = mongoose.model('Actor', schema, collectionName)
|
||||
*
|
||||
* @param {String} name model name
|
||||
* @param {Schema} [schema]
|
||||
* @param {String} [collection] name (optional, induced from model name)
|
||||
* @param {Boolean} [skipInit] whether to skip initialization (defaults to false)
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.model = function (name, schema, collection, skipInit) {
|
||||
if ('string' == typeof schema) {
|
||||
collection = schema;
|
||||
schema = false;
|
||||
}
|
||||
|
||||
if (utils.isObject(schema) && !(schema instanceof Schema)) {
|
||||
schema = new Schema(schema);
|
||||
}
|
||||
|
||||
if ('boolean' === typeof collection) {
|
||||
skipInit = collection;
|
||||
collection = null;
|
||||
}
|
||||
|
||||
// handle internal options from connection.model()
|
||||
var options;
|
||||
if (skipInit && utils.isObject(skipInit)) {
|
||||
options = skipInit;
|
||||
skipInit = true;
|
||||
} else {
|
||||
options = {};
|
||||
}
|
||||
|
||||
// look up schema for the collection.
|
||||
if (!this.modelSchemas[name]) {
|
||||
if (schema) {
|
||||
// cache it so we only apply plugins once
|
||||
this.modelSchemas[name] = schema;
|
||||
this._applyPlugins(schema);
|
||||
} else {
|
||||
throw new mongoose.Error.MissingSchemaError(name);
|
||||
}
|
||||
}
|
||||
|
||||
var model;
|
||||
var sub;
|
||||
|
||||
// connection.model() may be passing a different schema for
|
||||
// an existing model name. in this case don't read from cache.
|
||||
if (this.models[name] && false !== options.cache) {
|
||||
if (schema instanceof Schema && schema != this.models[name].schema) {
|
||||
throw new mongoose.Error.OverwriteModelError(name);
|
||||
}
|
||||
|
||||
if (collection) {
|
||||
// subclass current model with alternate collection
|
||||
model = this.models[name];
|
||||
schema = model.prototype.schema;
|
||||
sub = model.__subclass(this.connection, schema, collection);
|
||||
// do not cache the sub model
|
||||
return sub;
|
||||
}
|
||||
|
||||
return this.models[name];
|
||||
}
|
||||
|
||||
// ensure a schema exists
|
||||
if (!schema) {
|
||||
schema = this.modelSchemas[name];
|
||||
if (!schema) {
|
||||
throw new mongoose.Error.MissingSchemaError(name);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply relevant "global" options to the schema
|
||||
if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization;
|
||||
|
||||
|
||||
if (!collection) {
|
||||
collection = schema.get('collection') || format(name, schema.options);
|
||||
}
|
||||
|
||||
var connection = options.connection || this.connection;
|
||||
model = Model.compile(name, schema, collection, connection, this);
|
||||
|
||||
if (!skipInit) {
|
||||
model.init();
|
||||
}
|
||||
|
||||
if (false === options.cache) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return this.models[name] = model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of model names created on this instance of Mongoose.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _Does not include names of models created using `connection.model()`._
|
||||
*
|
||||
* @api public
|
||||
* @return {Array}
|
||||
*/
|
||||
|
||||
Mongoose.prototype.modelNames = function () {
|
||||
var names = Object.keys(this.models);
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies global plugins to `schema`.
|
||||
*
|
||||
* @param {Schema} schema
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Mongoose.prototype._applyPlugins = function (schema) {
|
||||
for (var i = 0, l = this.plugins.length; i < l; i++) {
|
||||
schema.plugin(this.plugins[i][0], this.plugins[i][1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Declares a global plugin executed on all Schemas.
|
||||
*
|
||||
* Equivalent to calling `.plugin(fn)` on each Schema you create.
|
||||
*
|
||||
* @param {Function} fn plugin callback
|
||||
* @param {Object} [opts] optional options
|
||||
* @return {Mongoose} this
|
||||
* @see plugins ./plugins.html
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.plugin = function (fn, opts) {
|
||||
this.plugins.push([fn, opts]);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* The default connection of the mongoose module.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* mongoose.connect(...);
|
||||
* mongoose.connection.on('error', cb);
|
||||
*
|
||||
* This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model).
|
||||
*
|
||||
* @property connection
|
||||
* @return {Connection}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.__defineGetter__('connection', function(){
|
||||
return this.connections[0];
|
||||
});
|
||||
|
||||
/*!
|
||||
* Driver depentend APIs
|
||||
*/
|
||||
|
||||
var driver = global.MONGOOSE_DRIVER_PATH || 'node-mongodb-native';
|
||||
|
||||
/*!
|
||||
* Connection
|
||||
*/
|
||||
|
||||
var Connection = require('./drivers/' + driver + '/connection');
|
||||
|
||||
/*!
|
||||
* Collection
|
||||
*/
|
||||
|
||||
var Collection = require('./drivers/' + driver + '/collection');
|
||||
|
||||
/**
|
||||
* The Mongoose Collection constructor
|
||||
*
|
||||
* @method Collection
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Collection = Collection;
|
||||
|
||||
/**
|
||||
* The Mongoose [Connection](#connection_Connection) constructor
|
||||
*
|
||||
* @method Connection
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Connection = Connection;
|
||||
|
||||
/**
|
||||
* The Mongoose version
|
||||
*
|
||||
* @property version
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.version = pkg.version;
|
||||
|
||||
/**
|
||||
* The Mongoose constructor
|
||||
*
|
||||
* The exports of the mongoose module is an instance of this class.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* var mongoose2 = new mongoose.Mongoose();
|
||||
*
|
||||
* @method Mongoose
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Mongoose = Mongoose;
|
||||
|
||||
/**
|
||||
* The Mongoose [Schema](#schema_Schema) constructor
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* var Schema = mongoose.Schema;
|
||||
* var CatSchema = new Schema(..);
|
||||
*
|
||||
* @method Schema
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Schema = Schema;
|
||||
|
||||
/**
|
||||
* The Mongoose [SchemaType](#schematype_SchemaType) constructor
|
||||
*
|
||||
* @method SchemaType
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.SchemaType = SchemaType;
|
||||
|
||||
/**
|
||||
* The various Mongoose SchemaTypes.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _Alias of mongoose.Schema.Types for backwards compatibility._
|
||||
*
|
||||
* @property SchemaTypes
|
||||
* @see Schema.SchemaTypes #schema_Schema.Types
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.SchemaTypes = Schema.Types;
|
||||
|
||||
/**
|
||||
* The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
|
||||
*
|
||||
* @method VirtualType
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.VirtualType = VirtualType;
|
||||
|
||||
/**
|
||||
* The various Mongoose Types.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var mongoose = require('mongoose');
|
||||
* var array = mongoose.Types.Array;
|
||||
*
|
||||
* ####Types:
|
||||
*
|
||||
* - [ObjectId](#types-objectid-js)
|
||||
* - [Buffer](#types-buffer-js)
|
||||
* - [SubDocument](#types-embedded-js)
|
||||
* - [Array](#types-array-js)
|
||||
* - [DocumentArray](#types-documentarray-js)
|
||||
*
|
||||
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
|
||||
*
|
||||
* var ObjectId = mongoose.Types.ObjectId;
|
||||
* var id1 = new ObjectId;
|
||||
*
|
||||
* @property Types
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Types = Types;
|
||||
|
||||
/**
|
||||
* The Mongoose [Query](#query_Query) constructor.
|
||||
*
|
||||
* @method Query
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Query = Query;
|
||||
|
||||
/**
|
||||
* The Mongoose [Promise](#promise_Promise) constructor.
|
||||
*
|
||||
* @method Promise
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Promise = Promise;
|
||||
|
||||
/**
|
||||
* The Mongoose [Model](#model_Model) constructor.
|
||||
*
|
||||
* @method Model
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Model = Model;
|
||||
|
||||
/**
|
||||
* The Mongoose [Document](#document-js) constructor.
|
||||
*
|
||||
* @method Document
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Document = Document;
|
||||
|
||||
/**
|
||||
* The [MongooseError](#error_MongooseError) constructor.
|
||||
*
|
||||
* @method Error
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.Error = require('./error');
|
||||
|
||||
/**
|
||||
* The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
|
||||
*
|
||||
* @property mongo
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.mongo = require('mongodb');
|
||||
|
||||
/**
|
||||
* The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
|
||||
*
|
||||
* @property mquery
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mongoose.prototype.mquery = require('mquery');
|
||||
|
||||
/*!
|
||||
* The exports object is an instance of Mongoose.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
var mongoose = module.exports = exports = new Mongoose;
|
||||
31
node_modules/mongoose/lib/internal.js
generated
vendored
Normal file
31
node_modules/mongoose/lib/internal.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
/*!
|
||||
* Dependencies
|
||||
*/
|
||||
|
||||
var StateMachine = require('./statemachine')
|
||||
var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore');
|
||||
|
||||
module.exports = exports = InternalCache;
|
||||
|
||||
function InternalCache () {
|
||||
this.strictMode = undefined;
|
||||
this.selected = undefined;
|
||||
this.shardval = undefined;
|
||||
this.saveError = undefined;
|
||||
this.validationError = undefined;
|
||||
this.adhocPaths = undefined;
|
||||
this.removing = undefined;
|
||||
this.inserting = undefined;
|
||||
this.version = undefined;
|
||||
this.getters = {};
|
||||
this._id = undefined;
|
||||
this.populate = undefined; // what we want to populate in this doc
|
||||
this.populated = undefined;// the _ids that have been populated
|
||||
this.wasPopulated = false; // if this doc was the result of a population
|
||||
this.scope = undefined;
|
||||
this.activePaths = new ActiveRoster;
|
||||
|
||||
// embedded docs
|
||||
this.ownerDocument = undefined;
|
||||
this.fullPath = undefined;
|
||||
}
|
||||
2854
node_modules/mongoose/lib/model.js
generated
vendored
Normal file
2854
node_modules/mongoose/lib/model.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
259
node_modules/mongoose/lib/promise.js
generated
vendored
Normal file
259
node_modules/mongoose/lib/promise.js
generated
vendored
Normal file
@@ -0,0 +1,259 @@
|
||||
/*!
|
||||
* Module dependencies
|
||||
*/
|
||||
|
||||
var MPromise = require('mpromise');
|
||||
var util = require('util');
|
||||
|
||||
/**
|
||||
* Promise constructor.
|
||||
*
|
||||
* Promises are returned from executed queries. Example:
|
||||
*
|
||||
* var query = Candy.find({ bar: true });
|
||||
* var promise = query.exec();
|
||||
*
|
||||
* @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature
|
||||
* @inherits mpromise https://github.com/aheckmann/mpromise
|
||||
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
|
||||
* @event `err`: Emits when the promise is rejected
|
||||
* @event `complete`: Emits when the promise is fulfilled
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Promise (fn) {
|
||||
MPromise.call(this, fn);
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherit from mpromise
|
||||
*/
|
||||
|
||||
Promise.prototype = Object.create(MPromise.prototype, {
|
||||
constructor: {
|
||||
value: Promise
|
||||
, enumerable: false
|
||||
, writable: true
|
||||
, configurable: true
|
||||
}
|
||||
});
|
||||
|
||||
/*!
|
||||
* Override event names for backward compatibility.
|
||||
*/
|
||||
|
||||
Promise.SUCCESS = 'complete';
|
||||
Promise.FAILURE = 'err';
|
||||
|
||||
/**
|
||||
* Adds `listener` to the `event`.
|
||||
*
|
||||
* If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event.
|
||||
*
|
||||
* @see mpromise#on https://github.com/aheckmann/mpromise#on
|
||||
* @method on
|
||||
* @memberOf Promise
|
||||
* @param {String} event
|
||||
* @param {Function} listener
|
||||
* @return {Promise} this
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Rejects this promise with `reason`.
|
||||
*
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
*
|
||||
* @see mpromise#reject https://github.com/aheckmann/mpromise#reject
|
||||
* @method reject
|
||||
* @memberOf Promise
|
||||
* @param {Object|String|Error} reason
|
||||
* @return {Promise} this
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Rejects this promise with `err`.
|
||||
*
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
*
|
||||
* Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`.
|
||||
*
|
||||
* @api public
|
||||
* @param {Error|String} err
|
||||
* @return {Promise} this
|
||||
*/
|
||||
|
||||
Promise.prototype.error = function (err) {
|
||||
if (!(err instanceof Error)) {
|
||||
if (err instanceof Object) {
|
||||
err = util.inspect(err);
|
||||
}
|
||||
err = new Error(err);
|
||||
}
|
||||
return this.reject(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed.
|
||||
*
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
*
|
||||
* `err` will be cast to an Error if not already instanceof Error.
|
||||
*
|
||||
* _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._
|
||||
*
|
||||
* @param {Error} [err] error or null
|
||||
* @param {Object} [val] value to fulfill the promise with
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Promise.prototype.resolve = function (err) {
|
||||
if (err) return this.error(err);
|
||||
return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1));
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a single function as a listener to both err and complete.
|
||||
*
|
||||
* It will be executed with traditional node.js argument position when the promise is resolved.
|
||||
*
|
||||
* promise.addBack(function (err, args...) {
|
||||
* if (err) return handleError(err);
|
||||
* console.log('success');
|
||||
* })
|
||||
*
|
||||
* Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve).
|
||||
*
|
||||
* _Deprecated. Use `onResolve` instead._
|
||||
*
|
||||
* @method addBack
|
||||
* @param {Function} listener
|
||||
* @return {Promise} this
|
||||
* @deprecated
|
||||
*/
|
||||
|
||||
Promise.prototype.addBack = Promise.prototype.onResolve;
|
||||
|
||||
/**
|
||||
* Fulfills this promise with passed arguments.
|
||||
*
|
||||
* @method fulfill
|
||||
* @receiver Promise
|
||||
* @see https://github.com/aheckmann/mpromise#fulfill
|
||||
* @param {any} args
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fulfills this promise with passed arguments.
|
||||
*
|
||||
* Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).
|
||||
*
|
||||
* _Deprecated. Use `fulfill` instead._
|
||||
*
|
||||
* @method complete
|
||||
* @receiver Promise
|
||||
* @param {any} args
|
||||
* @api public
|
||||
* @deprecated
|
||||
*/
|
||||
|
||||
Promise.prototype.complete = MPromise.prototype.fulfill;
|
||||
|
||||
/**
|
||||
* Adds a listener to the `complete` (success) event.
|
||||
*
|
||||
* Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill).
|
||||
*
|
||||
* _Deprecated. Use `onFulfill` instead._
|
||||
*
|
||||
* @method addCallback
|
||||
* @param {Function} listener
|
||||
* @return {Promise} this
|
||||
* @api public
|
||||
* @deprecated
|
||||
*/
|
||||
|
||||
Promise.prototype.addCallback = Promise.prototype.onFulfill;
|
||||
|
||||
/**
|
||||
* Adds a listener to the `err` (rejected) event.
|
||||
*
|
||||
* Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject).
|
||||
*
|
||||
* _Deprecated. Use `onReject` instead._
|
||||
*
|
||||
* @method addErrback
|
||||
* @param {Function} listener
|
||||
* @return {Promise} this
|
||||
* @api public
|
||||
* @deprecated
|
||||
*/
|
||||
|
||||
Promise.prototype.addErrback = Promise.prototype.onReject;
|
||||
|
||||
/**
|
||||
* Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.
|
||||
*
|
||||
* Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
|
||||
* promise.then(function (meetups) {
|
||||
* var ids = meetups.map(function (m) {
|
||||
* return m._id;
|
||||
* });
|
||||
* return People.find({ meetups: { $in: ids }).exec();
|
||||
* }).then(function (people) {
|
||||
* if (people.length < 10000) {
|
||||
* throw new Error('Too few people!!!');
|
||||
* } else {
|
||||
* throw new Error('Still need more people!!!');
|
||||
* }
|
||||
* }).then(null, function (err) {
|
||||
* assert.ok(err instanceof Error);
|
||||
* });
|
||||
*
|
||||
* @see promises-A+ https://github.com/promises-aplus/promises-spec
|
||||
* @see mpromise#then https://github.com/aheckmann/mpromise#then
|
||||
* @method then
|
||||
* @memberOf Promise
|
||||
* @param {Function} onFulFill
|
||||
* @param {Function} onReject
|
||||
* @return {Promise} newPromise
|
||||
*/
|
||||
|
||||
/**
|
||||
* Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var p = new Promise;
|
||||
* p.then(function(){ throw new Error('shucks') });
|
||||
* setTimeout(function () {
|
||||
* p.fulfill();
|
||||
* // error was caught and swallowed by the promise returned from
|
||||
* // p.then(). we either have to always register handlers on
|
||||
* // the returned promises or we can do the following...
|
||||
* }, 10);
|
||||
*
|
||||
* // this time we use .end() which prevents catching thrown errors
|
||||
* var p = new Promise;
|
||||
* var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--
|
||||
* setTimeout(function () {
|
||||
* p.fulfill(); // throws "shucks"
|
||||
* }, 10);
|
||||
*
|
||||
* @api public
|
||||
* @see mpromise#end https://github.com/aheckmann/mpromise#end
|
||||
* @method end
|
||||
* @memberOf Promise
|
||||
*/
|
||||
|
||||
/*!
|
||||
* expose
|
||||
*/
|
||||
|
||||
module.exports = Promise;
|
||||
2961
node_modules/mongoose/lib/query.js
generated
vendored
Normal file
2961
node_modules/mongoose/lib/query.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
79
node_modules/mongoose/lib/queryhelpers.js
generated
vendored
Normal file
79
node_modules/mongoose/lib/queryhelpers.js
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies
|
||||
*/
|
||||
|
||||
var utils = require('./utils')
|
||||
|
||||
/*!
|
||||
* Prepare a set of path options for query population.
|
||||
*
|
||||
* @param {Query} query
|
||||
* @param {Object} options
|
||||
* @return {Array}
|
||||
*/
|
||||
|
||||
exports.preparePopulationOptions = function preparePopulationOptions (query, options) {
|
||||
var pop = utils.object.vals(query.options.populate);
|
||||
|
||||
// lean options should trickle through all queries
|
||||
if (options.lean) pop.forEach(makeLean);
|
||||
|
||||
return pop;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Prepare a set of path options for query population. This is the MongooseQuery
|
||||
* version
|
||||
*
|
||||
* @param {Query} query
|
||||
* @param {Object} options
|
||||
* @return {Array}
|
||||
*/
|
||||
|
||||
exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ (query, options) {
|
||||
var pop = utils.object.vals(query._mongooseOptions.populate);
|
||||
|
||||
// lean options should trickle through all queries
|
||||
if (options.lean) pop.forEach(makeLean);
|
||||
|
||||
return pop;
|
||||
}
|
||||
|
||||
/*!
|
||||
* If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
|
||||
* it returns an instance of the given model.
|
||||
*
|
||||
* @param {Model} model
|
||||
* @param {Object} doc
|
||||
* @param {Object} fields
|
||||
*
|
||||
* @return {Model}
|
||||
*/
|
||||
exports.createModel = function createModel(model, doc, fields) {
|
||||
var discriminatorMapping = model.schema
|
||||
? model.schema.discriminatorMapping
|
||||
: null;
|
||||
|
||||
var key = discriminatorMapping && discriminatorMapping.isRoot
|
||||
? discriminatorMapping.key
|
||||
: null;
|
||||
|
||||
if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) {
|
||||
return new model.discriminators[doc[key]](undefined, fields, true);
|
||||
}
|
||||
|
||||
return new model(undefined, fields, true);
|
||||
}
|
||||
|
||||
/*!
|
||||
* Set each path query option to lean
|
||||
*
|
||||
* @param {Object} option
|
||||
*/
|
||||
|
||||
function makeLean (option) {
|
||||
option.options || (option.options = {});
|
||||
option.options.lean = true;
|
||||
}
|
||||
|
||||
340
node_modules/mongoose/lib/querystream.js
generated
vendored
Normal file
340
node_modules/mongoose/lib/querystream.js
generated
vendored
Normal file
@@ -0,0 +1,340 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Stream = require('stream').Stream
|
||||
var utils = require('./utils')
|
||||
var helpers = require('./queryhelpers')
|
||||
var K = function(k){ return k }
|
||||
|
||||
/**
|
||||
* Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries.
|
||||
*
|
||||
* var stream = Model.find().stream();
|
||||
*
|
||||
* stream.on('data', function (doc) {
|
||||
* // do something with the mongoose document
|
||||
* }).on('error', function (err) {
|
||||
* // handle the error
|
||||
* }).on('close', function () {
|
||||
* // the stream is closed
|
||||
* });
|
||||
*
|
||||
*
|
||||
* The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams.
|
||||
*
|
||||
* Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream);
|
||||
*
|
||||
* ####Valid options
|
||||
*
|
||||
* - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`.
|
||||
*
|
||||
* ####Example
|
||||
*
|
||||
* // JSON.stringify all documents before emitting
|
||||
* var stream = Thing.find().stream({ transform: JSON.stringify });
|
||||
* stream.pipe(writeStream);
|
||||
*
|
||||
* _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._
|
||||
*
|
||||
* _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._
|
||||
*
|
||||
* @param {Query} query
|
||||
* @param {Object} [options]
|
||||
* @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream
|
||||
* @event `data`: emits a single Mongoose document
|
||||
* @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event.
|
||||
* @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function QueryStream (query, options) {
|
||||
Stream.call(this);
|
||||
|
||||
this.query = query;
|
||||
this.readable = true;
|
||||
this.paused = false;
|
||||
this._cursor = null;
|
||||
this._destroyed = null;
|
||||
this._fields = null;
|
||||
this._buffer = null;
|
||||
this._inline = T_INIT;
|
||||
this._running = false;
|
||||
this._transform = options && 'function' == typeof options.transform
|
||||
? options.transform
|
||||
: K;
|
||||
|
||||
// give time to hook up events
|
||||
var self = this;
|
||||
process.nextTick(function () {
|
||||
self._init();
|
||||
});
|
||||
}
|
||||
|
||||
/*!
|
||||
* Inherit from Stream
|
||||
*/
|
||||
|
||||
QueryStream.prototype.__proto__ = Stream.prototype;
|
||||
|
||||
/**
|
||||
* Flag stating whether or not this stream is readable.
|
||||
*
|
||||
* @property readable
|
||||
* @api public
|
||||
*/
|
||||
|
||||
QueryStream.prototype.readable;
|
||||
|
||||
/**
|
||||
* Flag stating whether or not this stream is paused.
|
||||
*
|
||||
* @property paused
|
||||
* @api public
|
||||
*/
|
||||
|
||||
QueryStream.prototype.paused;
|
||||
|
||||
// trampoline flags
|
||||
var T_INIT = 0;
|
||||
var T_IDLE = 1;
|
||||
var T_CONT = 2;
|
||||
|
||||
/**
|
||||
* Initializes the query.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
QueryStream.prototype._init = function () {
|
||||
if (this._destroyed) return;
|
||||
|
||||
var query = this.query
|
||||
, model = query.model
|
||||
, options = query._optionsForExec(model)
|
||||
, self = this
|
||||
|
||||
try {
|
||||
query.cast(model);
|
||||
} catch (err) {
|
||||
return self.destroy(err);
|
||||
}
|
||||
|
||||
self._fields = utils.clone(query._fields);
|
||||
options.fields = query._castFields(self._fields);
|
||||
|
||||
model.collection.find(query._conditions, options, function (err, cursor) {
|
||||
if (err) return self.destroy(err);
|
||||
self._cursor = cursor;
|
||||
self._next();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Trampoline for pulling the next doc from cursor.
|
||||
*
|
||||
* @see QueryStream#__next #querystream_QueryStream-__next
|
||||
* @api private
|
||||
*/
|
||||
|
||||
QueryStream.prototype._next = function _next () {
|
||||
if (this.paused || this._destroyed) {
|
||||
return this._running = false;
|
||||
}
|
||||
|
||||
this._running = true;
|
||||
|
||||
if (this._buffer && this._buffer.length) {
|
||||
var arg;
|
||||
while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) {
|
||||
this._onNextObject.apply(this, arg);
|
||||
}
|
||||
}
|
||||
|
||||
// avoid stack overflows with large result sets.
|
||||
// trampoline instead of recursion.
|
||||
while (this.__next()) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls the next doc from the cursor.
|
||||
*
|
||||
* @see QueryStream#_next #querystream_QueryStream-_next
|
||||
* @api private
|
||||
*/
|
||||
|
||||
QueryStream.prototype.__next = function () {
|
||||
if (this.paused || this._destroyed)
|
||||
return this._running = false;
|
||||
|
||||
var self = this;
|
||||
self._inline = T_INIT;
|
||||
|
||||
self._cursor.nextObject(function cursorcb (err, doc) {
|
||||
self._onNextObject(err, doc);
|
||||
});
|
||||
|
||||
// if onNextObject() was already called in this tick
|
||||
// return ourselves to the trampoline.
|
||||
if (T_CONT === this._inline) {
|
||||
return true;
|
||||
} else {
|
||||
// onNextObject() hasn't fired yet. tell onNextObject
|
||||
// that its ok to call _next b/c we are not within
|
||||
// the trampoline anymore.
|
||||
this._inline = T_IDLE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms raw `doc`s returned from the cursor into a model instance.
|
||||
*
|
||||
* @param {Error|null} err
|
||||
* @param {Object} doc
|
||||
* @api private
|
||||
*/
|
||||
|
||||
QueryStream.prototype._onNextObject = function _onNextObject (err, doc) {
|
||||
if (this._destroyed) return;
|
||||
|
||||
if (this.paused) {
|
||||
this._buffer || (this._buffer = []);
|
||||
this._buffer.push([err, doc]);
|
||||
return this._running = false;
|
||||
}
|
||||
|
||||
if (err) return this.destroy(err);
|
||||
|
||||
// when doc is null we hit the end of the cursor
|
||||
if (!doc) {
|
||||
this.emit('end');
|
||||
return this.destroy();
|
||||
}
|
||||
|
||||
var opts = this.query._mongooseOptions;
|
||||
|
||||
if (!opts.populate) {
|
||||
return true === opts.lean ?
|
||||
emit(this, doc) :
|
||||
createAndEmit(this, null, doc);
|
||||
}
|
||||
|
||||
var self = this;
|
||||
var pop = helpers.preparePopulationOptionsMQ(self.query, self.query._mongooseOptions);
|
||||
|
||||
self.query.model.populate(doc, pop, function (err, doc) {
|
||||
if (err) return self.destroy(err);
|
||||
return true === opts.lean ?
|
||||
emit(self, doc) :
|
||||
createAndEmit(self, pop, doc);
|
||||
});
|
||||
}
|
||||
|
||||
function createAndEmit (self, populatedIds, doc) {
|
||||
var instance = helpers.createModel(self.query.model, doc, self._fields);
|
||||
var opts = populatedIds ?
|
||||
{ populated: populatedIds } :
|
||||
undefined;
|
||||
|
||||
instance.init(doc, opts, function (err) {
|
||||
if (err) return self.destroy(err);
|
||||
emit(self, instance);
|
||||
});
|
||||
}
|
||||
|
||||
/*!
|
||||
* Emit a data event and manage the trampoline state
|
||||
*/
|
||||
|
||||
function emit (self, doc) {
|
||||
self.emit('data', self._transform(doc));
|
||||
|
||||
// trampoline management
|
||||
if (T_IDLE === self._inline) {
|
||||
// no longer in trampoline. restart it.
|
||||
self._next();
|
||||
} else {
|
||||
// in a trampoline. tell __next that its
|
||||
// ok to continue jumping.
|
||||
self._inline = T_CONT;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pauses this stream.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
QueryStream.prototype.pause = function () {
|
||||
this.paused = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes this stream.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
QueryStream.prototype.resume = function () {
|
||||
this.paused = false;
|
||||
|
||||
if (!this._cursor) {
|
||||
// cannot start if not initialized
|
||||
return;
|
||||
}
|
||||
|
||||
// are we within the trampoline?
|
||||
if (T_INIT === this._inline) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this._running) {
|
||||
// outside QueryStream control, need manual restart
|
||||
return this._next();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the stream, closing the underlying cursor. No more events will be emitted.
|
||||
*
|
||||
* @param {Error} [err]
|
||||
* @api public
|
||||
*/
|
||||
|
||||
QueryStream.prototype.destroy = function (err) {
|
||||
if (this._destroyed) return;
|
||||
this._destroyed = true;
|
||||
this._running = false;
|
||||
this.readable = false;
|
||||
|
||||
if (this._cursor) {
|
||||
this._cursor.close();
|
||||
}
|
||||
|
||||
if (err) {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
this.emit('close');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pipes this query stream into another stream. This method is inherited from NodeJS Streams.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* query.stream().pipe(writeStream [, options])
|
||||
*
|
||||
* @method pipe
|
||||
* @memberOf QueryStream
|
||||
* @see NodeJS http://nodejs.org/api/stream.html
|
||||
* @api public
|
||||
*/
|
||||
|
||||
/*!
|
||||
* Module exports
|
||||
*/
|
||||
|
||||
module.exports = exports = QueryStream;
|
||||
1042
node_modules/mongoose/lib/schema.js
generated
vendored
Normal file
1042
node_modules/mongoose/lib/schema.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
397
node_modules/mongoose/lib/schema/array.js
generated
vendored
Normal file
397
node_modules/mongoose/lib/schema/array.js
generated
vendored
Normal file
@@ -0,0 +1,397 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var SchemaType = require('../schematype')
|
||||
, CastError = SchemaType.CastError
|
||||
, NumberSchema = require('./number')
|
||||
, Types = {
|
||||
Boolean: require('./boolean')
|
||||
, Date: require('./date')
|
||||
, Number: require('./number')
|
||||
, String: require('./string')
|
||||
, ObjectId: require('./objectid')
|
||||
, Buffer: require('./buffer')
|
||||
}
|
||||
, MongooseArray = require('../types').Array
|
||||
, EmbeddedDoc = require('../types').Embedded
|
||||
, Mixed = require('./mixed')
|
||||
, cast = require('../cast')
|
||||
, utils = require('../utils')
|
||||
, isMongooseObject = utils.isMongooseObject
|
||||
|
||||
/**
|
||||
* Array SchemaType constructor
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {SchemaType} cast
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function SchemaArray (key, cast, options) {
|
||||
if (cast) {
|
||||
var castOptions = {};
|
||||
|
||||
if ('Object' === utils.getFunctionName(cast.constructor)) {
|
||||
if (cast.type) {
|
||||
// support { type: Woot }
|
||||
castOptions = utils.clone(cast); // do not alter user arguments
|
||||
delete castOptions.type;
|
||||
cast = cast.type;
|
||||
} else {
|
||||
cast = Mixed;
|
||||
}
|
||||
}
|
||||
|
||||
// support { type: 'String' }
|
||||
var name = 'string' == typeof cast
|
||||
? cast
|
||||
: utils.getFunctionName(cast);
|
||||
|
||||
var caster = name in Types
|
||||
? Types[name]
|
||||
: cast;
|
||||
|
||||
this.casterConstructor = caster;
|
||||
this.caster = new caster(null, castOptions);
|
||||
if (!(this.caster instanceof EmbeddedDoc)) {
|
||||
this.caster.path = key;
|
||||
}
|
||||
}
|
||||
|
||||
SchemaType.call(this, key, options, 'Array');
|
||||
|
||||
var self = this
|
||||
, defaultArr
|
||||
, fn;
|
||||
|
||||
if (this.defaultValue) {
|
||||
defaultArr = this.defaultValue;
|
||||
fn = 'function' == typeof defaultArr;
|
||||
}
|
||||
|
||||
this.default(function(){
|
||||
var arr = fn ? defaultArr() : defaultArr || [];
|
||||
return new MongooseArray(arr, self.path, this);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
SchemaArray.schemaName = 'Array';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
SchemaArray.prototype = Object.create( SchemaType.prototype );
|
||||
SchemaArray.prototype.constructor = SchemaArray;
|
||||
|
||||
/**
|
||||
* Check required
|
||||
*
|
||||
* @param {Array} value
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaArray.prototype.checkRequired = function (value) {
|
||||
return !!(value && value.length);
|
||||
};
|
||||
|
||||
/**
|
||||
* Overrides the getters application for the population special-case
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Object} scope
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaArray.prototype.applyGetters = function (value, scope) {
|
||||
if (this.caster.options && this.caster.options.ref) {
|
||||
// means the object id was populated
|
||||
return value;
|
||||
}
|
||||
|
||||
return SchemaType.prototype.applyGetters.call(this, value, scope);
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts values for set().
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Document} doc document that triggers the casting
|
||||
* @param {Boolean} init whether this is an initialization cast
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaArray.prototype.cast = function (value, doc, init) {
|
||||
if (Array.isArray(value)) {
|
||||
|
||||
if (!value.length && doc) {
|
||||
var indexes = doc.schema.indexedPaths();
|
||||
|
||||
for (var i = 0, l = indexes.length; i < l; ++i) {
|
||||
var pathIndex = indexes[i][0][this.path];
|
||||
if ('2dsphere' === pathIndex || '2d' === pathIndex) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!(value && value.isMongooseArray)) {
|
||||
value = new MongooseArray(value, this.path, doc);
|
||||
}
|
||||
|
||||
if (this.caster) {
|
||||
try {
|
||||
for (var i = 0, l = value.length; i < l; i++) {
|
||||
value[i] = this.caster.cast(value[i], doc, init);
|
||||
}
|
||||
} catch (e) {
|
||||
// rethrow
|
||||
throw new CastError(e.type, value, this.path);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
} else {
|
||||
// gh-2442: if we're loading this from the db and its not an array, mark
|
||||
// the whole array as modified.
|
||||
if (!!doc && !!init) {
|
||||
doc.markModified(this.path);
|
||||
}
|
||||
return this.cast([value], doc, init);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts values for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} [value]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaArray.prototype.castForQuery = function ($conditional, value) {
|
||||
var handler
|
||||
, val;
|
||||
|
||||
if (arguments.length === 2) {
|
||||
handler = this.$conditionalHandlers[$conditional];
|
||||
|
||||
if (!handler) {
|
||||
throw new Error("Can't use " + $conditional + " with Array.");
|
||||
}
|
||||
|
||||
val = handler.call(this, value);
|
||||
|
||||
} else {
|
||||
|
||||
val = $conditional;
|
||||
var proto = this.casterConstructor.prototype;
|
||||
var method = proto.castForQuery || proto.cast;
|
||||
var caster = this.caster;
|
||||
|
||||
if (Array.isArray(val)) {
|
||||
val = val.map(function (v) {
|
||||
if (method) v = method.call(caster, v);
|
||||
return isMongooseObject(v) ?
|
||||
v.toObject({ virtuals: false }) :
|
||||
v;
|
||||
});
|
||||
|
||||
} else if (method) {
|
||||
val = method.call(caster, val);
|
||||
}
|
||||
}
|
||||
|
||||
return val && isMongooseObject(val) ?
|
||||
val.toObject({ virtuals: false }) :
|
||||
val;
|
||||
};
|
||||
|
||||
/*!
|
||||
* @ignore
|
||||
*
|
||||
* $atomic cast helpers
|
||||
*/
|
||||
|
||||
function castToNumber (val) {
|
||||
return Types.Number.prototype.cast.call(this, val);
|
||||
}
|
||||
|
||||
function castArraysOfNumbers (arr, self) {
|
||||
self || (self = this);
|
||||
|
||||
arr.forEach(function (v, i) {
|
||||
if (Array.isArray(v)) {
|
||||
castArraysOfNumbers(v, self);
|
||||
} else {
|
||||
arr[i] = castToNumber.call(self, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function cast$near (val) {
|
||||
if (Array.isArray(val)) {
|
||||
castArraysOfNumbers(val, this);
|
||||
return val;
|
||||
}
|
||||
|
||||
if (val && val.$geometry) {
|
||||
return cast$geometry(val, this);
|
||||
}
|
||||
|
||||
return SchemaArray.prototype.castForQuery.call(this, val);
|
||||
}
|
||||
|
||||
function cast$geometry (val, self) {
|
||||
switch (val.$geometry.type) {
|
||||
case 'Polygon':
|
||||
case 'LineString':
|
||||
case 'Point':
|
||||
castArraysOfNumbers(val.$geometry.coordinates, self);
|
||||
break;
|
||||
default:
|
||||
// ignore unknowns
|
||||
break;
|
||||
}
|
||||
|
||||
if (val.$maxDistance) {
|
||||
val.$maxDistance = castToNumber.call(self, val.$maxDistance);
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
function cast$within (val) {
|
||||
var self = this;
|
||||
|
||||
if (val.$maxDistance) {
|
||||
val.$maxDistance = castToNumber.call(self, val.$maxDistance);
|
||||
}
|
||||
|
||||
if (val.$box || val.$polygon) {
|
||||
var type = val.$box ? '$box' : '$polygon';
|
||||
val[type].forEach(function (arr) {
|
||||
if (!Array.isArray(arr)) {
|
||||
var msg = 'Invalid $within $box argument. '
|
||||
+ 'Expected an array, received ' + arr;
|
||||
throw new TypeError(msg);
|
||||
}
|
||||
arr.forEach(function (v, i) {
|
||||
arr[i] = castToNumber.call(this, v);
|
||||
});
|
||||
})
|
||||
} else if (val.$center || val.$centerSphere) {
|
||||
var type = val.$center ? '$center' : '$centerSphere';
|
||||
val[type].forEach(function (item, i) {
|
||||
if (Array.isArray(item)) {
|
||||
item.forEach(function (v, j) {
|
||||
item[j] = castToNumber.call(this, v);
|
||||
});
|
||||
} else {
|
||||
val[type][i] = castToNumber.call(this, item);
|
||||
}
|
||||
})
|
||||
} else if (val.$geometry) {
|
||||
cast$geometry(val, this);
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
function cast$all (val) {
|
||||
if (!Array.isArray(val)) {
|
||||
val = [val];
|
||||
}
|
||||
|
||||
val = val.map(function (v) {
|
||||
if (utils.isObject(v)) {
|
||||
var o = {};
|
||||
o[this.path] = v;
|
||||
return cast(this.casterConstructor.schema, o)[this.path];
|
||||
}
|
||||
return v;
|
||||
}, this);
|
||||
|
||||
return this.castForQuery(val);
|
||||
}
|
||||
|
||||
function cast$elemMatch (val) {
|
||||
var hasDollarKey = false;
|
||||
var keys = Object.keys(val);
|
||||
var numKeys = keys.length;
|
||||
var key;
|
||||
var value;
|
||||
for (var i = 0; i < numKeys; ++i) {
|
||||
var key = keys[i];
|
||||
var value = val[key];
|
||||
if (key.indexOf('$') === 0 && value) {
|
||||
val[key] = this.castForQuery(key, value);
|
||||
hasDollarKey = true;
|
||||
}
|
||||
}
|
||||
if (hasDollarKey) {
|
||||
return val;
|
||||
}
|
||||
|
||||
return cast(this.casterConstructor.schema, val);
|
||||
}
|
||||
|
||||
function cast$geoIntersects (val) {
|
||||
var geo = val.$geometry;
|
||||
if (!geo) return;
|
||||
|
||||
cast$geometry(val, this);
|
||||
return val;
|
||||
}
|
||||
|
||||
var handle = SchemaArray.prototype.$conditionalHandlers = {};
|
||||
|
||||
handle.$all = cast$all;
|
||||
handle.$options = String;
|
||||
handle.$elemMatch = cast$elemMatch;
|
||||
handle.$geoIntersects = cast$geoIntersects;
|
||||
handle.$or = handle.$and = function(val) {
|
||||
if (!Array.isArray(val)) {
|
||||
throw new TypeError('conditional $or/$and require array');
|
||||
}
|
||||
|
||||
var ret = [];
|
||||
for (var i = 0; i < val.length; ++i) {
|
||||
ret.push(cast(this.casterConstructor.schema, val[i]));
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
handle.$near =
|
||||
handle.$nearSphere = cast$near;
|
||||
|
||||
handle.$within =
|
||||
handle.$geoWithin = cast$within;
|
||||
|
||||
handle.$size =
|
||||
handle.$maxDistance = castToNumber;
|
||||
|
||||
handle.$eq =
|
||||
handle.$gt =
|
||||
handle.$gte =
|
||||
handle.$in =
|
||||
handle.$lt =
|
||||
handle.$lte =
|
||||
handle.$ne =
|
||||
handle.$nin =
|
||||
handle.$regex = SchemaArray.prototype.castForQuery;
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = SchemaArray;
|
||||
105
node_modules/mongoose/lib/schema/boolean.js
generated
vendored
Normal file
105
node_modules/mongoose/lib/schema/boolean.js
generated
vendored
Normal file
@@ -0,0 +1,105 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utils = require('../utils');
|
||||
|
||||
var SchemaType = require('../schematype');
|
||||
var utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Boolean SchemaType constructor.
|
||||
*
|
||||
* @param {String} path
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function SchemaBoolean (path, options) {
|
||||
SchemaType.call(this, path, options, 'Boolean');
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
SchemaBoolean.schemaName = 'Boolean';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
SchemaBoolean.prototype = Object.create( SchemaType.prototype );
|
||||
SchemaBoolean.prototype.constructor = SchemaBoolean;
|
||||
|
||||
/**
|
||||
* Required validator
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaBoolean.prototype.checkRequired = function (value) {
|
||||
return value === true || value === false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts to boolean
|
||||
*
|
||||
* @param {Object} value
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaBoolean.prototype.cast = function (value) {
|
||||
if (null === value) return value;
|
||||
if ('0' === value) return false;
|
||||
if ('true' === value) return true;
|
||||
if ('false' === value) return false;
|
||||
return !! value;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function handleArray (val) {
|
||||
var self = this;
|
||||
return val.map(function (m) {
|
||||
return self.cast(m);
|
||||
});
|
||||
}
|
||||
|
||||
SchemaBoolean.$conditionalHandlers =
|
||||
utils.options(SchemaType.prototype.$conditionalHandlers, {
|
||||
'$in': handleArray
|
||||
});
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} val
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaBoolean.prototype.castForQuery = function ($conditional, val) {
|
||||
var handler;
|
||||
if (2 === arguments.length) {
|
||||
handler = SchemaBoolean.$conditionalHandlers[$conditional];
|
||||
|
||||
if (handler) {
|
||||
return handler.call(this, val);
|
||||
}
|
||||
|
||||
return this.cast(val);
|
||||
}
|
||||
|
||||
return this.cast($conditional);
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = SchemaBoolean;
|
||||
183
node_modules/mongoose/lib/schema/buffer.js
generated
vendored
Normal file
183
node_modules/mongoose/lib/schema/buffer.js
generated
vendored
Normal file
@@ -0,0 +1,183 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utils = require('../utils');
|
||||
|
||||
var MongooseBuffer = require('../types').Buffer;
|
||||
var SchemaType = require('../schematype');
|
||||
|
||||
var Binary = MongooseBuffer.Binary;
|
||||
var CastError = SchemaType.CastError;
|
||||
var Document;
|
||||
|
||||
/**
|
||||
* Buffer SchemaType constructor
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {SchemaType} cast
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function SchemaBuffer (key, options) {
|
||||
SchemaType.call(this, key, options, 'Buffer');
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
SchemaBuffer.schemaName = 'Buffer';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
SchemaBuffer.prototype = Object.create( SchemaType.prototype );
|
||||
SchemaBuffer.prototype.constructor = SchemaBuffer;
|
||||
|
||||
/**
|
||||
* Check required
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaBuffer.prototype.checkRequired = function (value, doc) {
|
||||
if (SchemaType._isRef(this, value, doc, true)) {
|
||||
return null != value;
|
||||
} else {
|
||||
return !!(value && value.length);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts contents
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Document} doc document that triggers the casting
|
||||
* @param {Boolean} init
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaBuffer.prototype.cast = function (value, doc, init) {
|
||||
if (SchemaType._isRef(this, value, doc, init)) {
|
||||
// wait! we may need to cast this to a document
|
||||
|
||||
if (null == value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// lazy load
|
||||
Document || (Document = require('./../document'));
|
||||
|
||||
if (value instanceof Document) {
|
||||
value.$__.wasPopulated = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
// setting a populated path
|
||||
if (Buffer.isBuffer(value)) {
|
||||
return value;
|
||||
} else if (!utils.isObject(value)) {
|
||||
throw new CastError('buffer', value, this.path);
|
||||
}
|
||||
|
||||
// Handle the case where user directly sets a populated
|
||||
// path to a plain object; cast to the Model used in
|
||||
// the population query.
|
||||
var path = doc.$__fullPath(this.path);
|
||||
var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
var pop = owner.populated(path, true);
|
||||
var ret = new pop.options.model(value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// documents
|
||||
if (value && value._id) {
|
||||
value = value._id;
|
||||
}
|
||||
|
||||
if (value && value.isMongooseBuffer) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (Buffer.isBuffer(value)) {
|
||||
if (!value || !value.isMongooseBuffer) {
|
||||
value = new MongooseBuffer(value, [this.path, doc]);
|
||||
}
|
||||
|
||||
return value;
|
||||
} else if (value instanceof Binary) {
|
||||
var ret = new MongooseBuffer(value.value(true), [this.path, doc]);
|
||||
if (typeof value.sub_type !== 'number') {
|
||||
throw new CastError('buffer', value, this.path);
|
||||
}
|
||||
ret._subtype = value.sub_type;
|
||||
return ret;
|
||||
}
|
||||
|
||||
if (null === value) return value;
|
||||
|
||||
var type = typeof value;
|
||||
if ('string' == type || 'number' == type || Array.isArray(value)) {
|
||||
var ret = new MongooseBuffer(value, [this.path, doc]);
|
||||
return ret;
|
||||
}
|
||||
|
||||
throw new CastError('buffer', value, this.path);
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
function handleSingle (val) {
|
||||
return this.castForQuery(val);
|
||||
}
|
||||
|
||||
function handleArray (val) {
|
||||
var self = this;
|
||||
return val.map( function (m) {
|
||||
return self.castForQuery(m);
|
||||
});
|
||||
}
|
||||
|
||||
SchemaBuffer.prototype.$conditionalHandlers =
|
||||
utils.options(SchemaType.prototype.$conditionalHandlers, {
|
||||
'$gt' : handleSingle,
|
||||
'$gte': handleSingle,
|
||||
'$in' : handleArray,
|
||||
'$lt' : handleSingle,
|
||||
'$lte': handleSingle,
|
||||
'$ne' : handleSingle,
|
||||
'$nin': handleArray
|
||||
});
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} [value]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaBuffer.prototype.castForQuery = function ($conditional, val) {
|
||||
var handler;
|
||||
if (arguments.length === 2) {
|
||||
handler = this.$conditionalHandlers[$conditional];
|
||||
if (!handler)
|
||||
throw new Error("Can't use " + $conditional + " with Buffer.");
|
||||
return handler.call(this, val);
|
||||
} else {
|
||||
val = $conditional;
|
||||
return this.cast(val).toObject();
|
||||
}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = SchemaBuffer;
|
||||
293
node_modules/mongoose/lib/schema/date.js
generated
vendored
Normal file
293
node_modules/mongoose/lib/schema/date.js
generated
vendored
Normal file
@@ -0,0 +1,293 @@
|
||||
/*!
|
||||
* Module requirements.
|
||||
*/
|
||||
|
||||
var errorMessages = require('../error').messages
|
||||
var utils = require('../utils');
|
||||
|
||||
var SchemaType = require('../schematype');
|
||||
|
||||
var CastError = SchemaType.CastError;
|
||||
|
||||
/**
|
||||
* Date SchemaType constructor.
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function SchemaDate (key, options) {
|
||||
SchemaType.call(this, key, options, 'Date');
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
SchemaDate.schemaName = 'Date';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
SchemaDate.prototype = Object.create( SchemaType.prototype );
|
||||
SchemaDate.prototype.constructor = SchemaDate;
|
||||
|
||||
/**
|
||||
* Declares a TTL index (rounded to the nearest second) for _Date_ types only.
|
||||
*
|
||||
* This sets the `expiresAfterSeconds` index option available in MongoDB >= 2.1.2.
|
||||
* This index type is only compatible with Date types.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* // expire in 24 hours
|
||||
* new Schema({ createdAt: { type: Date, expires: 60*60*24 }});
|
||||
*
|
||||
* `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* // expire in 24 hours
|
||||
* new Schema({ createdAt: { type: Date, expires: '24h' }});
|
||||
*
|
||||
* // expire in 1.5 hours
|
||||
* new Schema({ createdAt: { type: Date, expires: '1.5h' }});
|
||||
*
|
||||
* // expire in 7 days
|
||||
* var schema = new Schema({ createdAt: Date });
|
||||
* schema.path('createdAt').expires('7d');
|
||||
*
|
||||
* @param {Number|String} when
|
||||
* @added 3.0.0
|
||||
* @return {SchemaType} this
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaDate.prototype.expires = function (when) {
|
||||
if (!this._index || 'Object' !== this._index.constructor.name) {
|
||||
this._index = {};
|
||||
}
|
||||
|
||||
this._index.expires = when;
|
||||
utils.expires(this._index);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Required validator for date
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaDate.prototype.checkRequired = function (value) {
|
||||
return value instanceof Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a minimum date validator.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ d: { type: Date, min: Date('1970-01-01') })
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ d: Date('1969-12-31') })
|
||||
* m.save(function (err) {
|
||||
* console.error(err) // validator error
|
||||
* m.d = Date('2014-12-08');
|
||||
* m.save() // success
|
||||
* })
|
||||
*
|
||||
* // custom error messages
|
||||
* // We can also use the special {MIN} token which will be replaced with the invalid value
|
||||
* var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
|
||||
* var schema = new Schema({ d: { type: Date, min: min })
|
||||
* var M = mongoose.model('M', schema);
|
||||
* var s= new M({ d: Date('1969-12-31') });
|
||||
* s.validate(function (err) {
|
||||
* console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01).
|
||||
* })
|
||||
*
|
||||
* @param {Date} value minimum date
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaDate.prototype.min = function (value, message) {
|
||||
if (this.minValidator) {
|
||||
this.validators = this.validators.filter(function (v) {
|
||||
return v.validator != this.minValidator;
|
||||
}, this);
|
||||
}
|
||||
|
||||
if (value) {
|
||||
var msg = message || errorMessages.Date.min;
|
||||
msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
|
||||
var self = this;
|
||||
this.validators.push({
|
||||
validator: this.minValidator = function (val) {
|
||||
var min = (value === Date.now ? value() : self.cast(value));
|
||||
return val === null || val.valueOf() >= min.valueOf();
|
||||
},
|
||||
message: msg,
|
||||
type: 'min'
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a maximum date validator.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ d: Date('2014-12-08') })
|
||||
* m.save(function (err) {
|
||||
* console.error(err) // validator error
|
||||
* m.d = Date('2013-12-31');
|
||||
* m.save() // success
|
||||
* })
|
||||
*
|
||||
* // custom error messages
|
||||
* // We can also use the special {MAX} token which will be replaced with the invalid value
|
||||
* var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
|
||||
* var schema = new Schema({ d: { type: Date, max: max })
|
||||
* var M = mongoose.model('M', schema);
|
||||
* var s= new M({ d: Date('2014-12-08') });
|
||||
* s.validate(function (err) {
|
||||
* console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
|
||||
* })
|
||||
*
|
||||
* @param {Date} maximum date
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaDate.prototype.max = function (value, message) {
|
||||
if (this.maxValidator) {
|
||||
this.validators = this.validators.filter(function(v){
|
||||
return v.validator != this.maxValidator;
|
||||
}, this);
|
||||
}
|
||||
|
||||
if (value) {
|
||||
var msg = message || errorMessages.Date.max;
|
||||
msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
|
||||
var self = this;
|
||||
this.validators.push({
|
||||
validator: this.maxValidator = function(val) {
|
||||
var max = (value === Date.now ? value() : self.cast(value));
|
||||
return val === null || val.valueOf() <= max.valueOf();
|
||||
},
|
||||
message: msg,
|
||||
type: 'max'
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts to date
|
||||
*
|
||||
* @param {Object} value to cast
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaDate.prototype.cast = function (value) {
|
||||
// If null or undefined
|
||||
if (value == null || value === '')
|
||||
return value;
|
||||
|
||||
if (value instanceof Date)
|
||||
return value;
|
||||
|
||||
var date;
|
||||
|
||||
// support for timestamps
|
||||
if (typeof value !== 'undefined') {
|
||||
if (value instanceof Number || 'number' == typeof value
|
||||
|| String(value) == Number(value)) {
|
||||
date = new Date(Number(value));
|
||||
} else if (value.toString) {
|
||||
// support for date strings
|
||||
date = new Date(value.toString());
|
||||
}
|
||||
|
||||
if (date.toString() != 'Invalid Date') {
|
||||
return date;
|
||||
}
|
||||
}
|
||||
|
||||
throw new CastError('date', value, this.path);
|
||||
};
|
||||
|
||||
/*!
|
||||
* Date Query casting.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function handleSingle (val) {
|
||||
return this.cast(val);
|
||||
}
|
||||
|
||||
function handleArray (val) {
|
||||
var self = this;
|
||||
return val.map( function (m) {
|
||||
return self.cast(m);
|
||||
});
|
||||
}
|
||||
|
||||
SchemaDate.prototype.$conditionalHandlers =
|
||||
utils.options(SchemaType.prototype.$conditionalHandlers, {
|
||||
'$all': handleArray,
|
||||
'$gt': handleSingle,
|
||||
'$gte': handleSingle,
|
||||
'$in': handleArray,
|
||||
'$lt': handleSingle,
|
||||
'$lte': handleSingle,
|
||||
'$ne': handleSingle,
|
||||
'$nin': handleArray
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} [value]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaDate.prototype.castForQuery = function ($conditional, val) {
|
||||
var handler;
|
||||
|
||||
if (2 !== arguments.length) {
|
||||
return this.cast($conditional);
|
||||
}
|
||||
|
||||
handler = this.$conditionalHandlers[$conditional];
|
||||
|
||||
if (!handler) {
|
||||
throw new Error("Can't use " + $conditional + " with Date.");
|
||||
}
|
||||
|
||||
return handler.call(this, val);
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = SchemaDate;
|
||||
249
node_modules/mongoose/lib/schema/documentarray.js
generated
vendored
Normal file
249
node_modules/mongoose/lib/schema/documentarray.js
generated
vendored
Normal file
@@ -0,0 +1,249 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var ArrayType = require('./array');
|
||||
var Document = require('../document');
|
||||
var MongooseDocumentArray = require('../types/documentarray');
|
||||
var SchemaType = require('../schematype');
|
||||
var Subdocument = require('../types/embedded');
|
||||
|
||||
/**
|
||||
* SubdocsArray SchemaType constructor
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {Schema} schema
|
||||
* @param {Object} options
|
||||
* @inherits SchemaArray
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function DocumentArray (key, schema, options) {
|
||||
|
||||
// compile an embedded document for this schema
|
||||
function EmbeddedDocument () {
|
||||
Subdocument.apply(this, arguments);
|
||||
}
|
||||
|
||||
EmbeddedDocument.prototype = Object.create(Subdocument.prototype);
|
||||
EmbeddedDocument.prototype.$__setSchema(schema);
|
||||
EmbeddedDocument.schema = schema;
|
||||
|
||||
// apply methods
|
||||
for (var i in schema.methods)
|
||||
EmbeddedDocument.prototype[i] = schema.methods[i];
|
||||
|
||||
// apply statics
|
||||
for (var i in schema.statics)
|
||||
EmbeddedDocument[i] = schema.statics[i];
|
||||
|
||||
EmbeddedDocument.options = options;
|
||||
this.schema = schema;
|
||||
|
||||
ArrayType.call(this, key, EmbeddedDocument, options);
|
||||
|
||||
this.schema = schema;
|
||||
var path = this.path;
|
||||
var fn = this.defaultValue;
|
||||
|
||||
this.default(function(){
|
||||
var arr = fn.call(this);
|
||||
if (!Array.isArray(arr)) arr = [arr];
|
||||
return new MongooseDocumentArray(arr, path, this);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
DocumentArray.schemaName = 'DocumentArray';
|
||||
|
||||
/*!
|
||||
* Inherits from ArrayType.
|
||||
*/
|
||||
DocumentArray.prototype = Object.create( ArrayType.prototype );
|
||||
DocumentArray.prototype.constructor = DocumentArray;
|
||||
|
||||
/**
|
||||
* Performs local validations first, then validations on each embedded doc
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
DocumentArray.prototype.doValidate = function (array, fn, scope) {
|
||||
SchemaType.prototype.doValidate.call(this, array, function (err) {
|
||||
if (err) {
|
||||
return fn(err);
|
||||
}
|
||||
|
||||
var count = array && array.length;
|
||||
var error;
|
||||
|
||||
if (!count) return fn();
|
||||
|
||||
// handle sparse arrays, do not use array.forEach which does not
|
||||
// iterate over sparse elements yet reports array.length including
|
||||
// them :(
|
||||
|
||||
for (var i = 0, len = count; i < len; ++i) {
|
||||
// sidestep sparse entries
|
||||
var doc = array[i];
|
||||
if (!doc) {
|
||||
--count || fn(error);
|
||||
continue;
|
||||
}
|
||||
|
||||
doc.validate(function (err) {
|
||||
if (err) {
|
||||
error = err;
|
||||
}
|
||||
--count || fn(error);
|
||||
});
|
||||
}
|
||||
}, scope);
|
||||
};
|
||||
|
||||
/**
|
||||
* Performs local validations first, then validations on each embedded doc.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* This method ignores the asynchronous validators.
|
||||
*
|
||||
* @return {MongooseError|undefined}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
DocumentArray.prototype.doValidateSync = function (array, scope) {
|
||||
var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
|
||||
if (schemaTypeError) return schemaTypeError;
|
||||
|
||||
var count = array && array.length
|
||||
, resultError = null;
|
||||
|
||||
if (!count) return;
|
||||
|
||||
// handle sparse arrays, do not use array.forEach which does not
|
||||
// iterate over sparse elements yet reports array.length including
|
||||
// them :(
|
||||
|
||||
for (var i = 0, len = count; i < len; ++i) {
|
||||
// only first error
|
||||
if ( resultError ) break;
|
||||
// sidestep sparse entries
|
||||
var doc = array[i];
|
||||
if (!doc) continue;
|
||||
|
||||
var subdocValidateError = doc.validateSync();
|
||||
|
||||
if (subdocValidateError) {
|
||||
resultError = subdocValidateError;
|
||||
}
|
||||
}
|
||||
|
||||
return resultError;
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts contents
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Document} document that triggers the casting
|
||||
* @api private
|
||||
*/
|
||||
|
||||
DocumentArray.prototype.cast = function (value, doc, init, prev) {
|
||||
var selected
|
||||
, subdoc
|
||||
, i
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
// gh-2442 mark whole array as modified if we're initializing a doc from
|
||||
// the db and the path isn't an array in the document
|
||||
if (!!doc && init) {
|
||||
doc.markModified(this.path);
|
||||
}
|
||||
return this.cast([value], doc, init, prev);
|
||||
}
|
||||
|
||||
if (!(value && value.isMongooseDocumentArray)) {
|
||||
value = new MongooseDocumentArray(value, this.path, doc);
|
||||
if (prev && prev._handlers) {
|
||||
for (var key in prev._handlers) {
|
||||
doc.removeListener(key, prev._handlers[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
i = value.length;
|
||||
|
||||
while (i--) {
|
||||
if (!(value[i] instanceof Subdocument) && value[i]) {
|
||||
if (init) {
|
||||
selected || (selected = scopePaths(this, doc.$__.selected, init));
|
||||
subdoc = new this.casterConstructor(null, value, true, selected, i);
|
||||
value[i] = subdoc.init(value[i]);
|
||||
} else {
|
||||
try {
|
||||
subdoc = prev.id(value[i]._id);
|
||||
} catch(e) {}
|
||||
|
||||
if (prev && subdoc) {
|
||||
// handle resetting doc with existing id but differing data
|
||||
// doc.array = [{ doc: 'val' }]
|
||||
subdoc.set(value[i]);
|
||||
// if set() is hooked it will have no return value
|
||||
// see gh-746
|
||||
value[i] = subdoc;
|
||||
} else {
|
||||
subdoc = new this.casterConstructor(value[i], value, undefined, undefined, i);
|
||||
// if set() is hooked it will have no return value
|
||||
// see gh-746
|
||||
value[i] = subdoc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Scopes paths selected in a query to this array.
|
||||
* Necessary for proper default application of subdocument values.
|
||||
*
|
||||
* @param {DocumentArray} array - the array to scope `fields` paths
|
||||
* @param {Object|undefined} fields - the root fields selected in the query
|
||||
* @param {Boolean|undefined} init - if we are being created part of a query result
|
||||
*/
|
||||
|
||||
function scopePaths (array, fields, init) {
|
||||
if (!(init && fields)) return undefined;
|
||||
|
||||
var path = array.path + '.'
|
||||
, keys = Object.keys(fields)
|
||||
, i = keys.length
|
||||
, selected = {}
|
||||
, hasKeys
|
||||
, key
|
||||
|
||||
while (i--) {
|
||||
key = keys[i];
|
||||
if (0 === key.indexOf(path)) {
|
||||
hasKeys || (hasKeys = true);
|
||||
selected[key.substring(path.length)] = fields[key];
|
||||
}
|
||||
}
|
||||
|
||||
return hasKeys && selected || undefined;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = DocumentArray;
|
||||
28
node_modules/mongoose/lib/schema/index.js
generated
vendored
Normal file
28
node_modules/mongoose/lib/schema/index.js
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
exports.String = require('./string');
|
||||
|
||||
exports.Number = require('./number');
|
||||
|
||||
exports.Boolean = require('./boolean');
|
||||
|
||||
exports.DocumentArray = require('./documentarray');
|
||||
|
||||
exports.Array = require('./array');
|
||||
|
||||
exports.Buffer = require('./buffer');
|
||||
|
||||
exports.Date = require('./date');
|
||||
|
||||
exports.ObjectId = require('./objectid');
|
||||
|
||||
exports.Mixed = require('./mixed');
|
||||
|
||||
// alias
|
||||
|
||||
exports.Oid = exports.ObjectId;
|
||||
exports.Object = exports.Mixed;
|
||||
exports.Bool = exports.Boolean;
|
||||
91
node_modules/mongoose/lib/schema/mixed.js
generated
vendored
Normal file
91
node_modules/mongoose/lib/schema/mixed.js
generated
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var SchemaType = require('../schematype');
|
||||
var utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Mixed SchemaType constructor.
|
||||
*
|
||||
* @param {String} path
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Mixed (path, options) {
|
||||
if (options && options.default) {
|
||||
var def = options.default;
|
||||
if (Array.isArray(def) && 0 === def.length) {
|
||||
// make sure empty array defaults are handled
|
||||
options.default = Array;
|
||||
} else if (!options.shared &&
|
||||
utils.isObject(def) &&
|
||||
0 === Object.keys(def).length) {
|
||||
// prevent odd "shared" objects between documents
|
||||
options.default = function () {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SchemaType.call(this, path, options, 'Mixed');
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
Mixed.schemaName = 'Mixed';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
Mixed.prototype = Object.create( SchemaType.prototype );
|
||||
Mixed.prototype.constructor = Mixed;
|
||||
|
||||
/**
|
||||
* Required validator
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Mixed.prototype.checkRequired = function (val) {
|
||||
return (val !== undefined) && (val !== null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts `val` for Mixed.
|
||||
*
|
||||
* _this is a no-op_
|
||||
*
|
||||
* @param {Object} value to cast
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Mixed.prototype.cast = function (val) {
|
||||
return val;
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $cond
|
||||
* @param {any} [val]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Mixed.prototype.castForQuery = function ($cond, val) {
|
||||
if (arguments.length === 2) return val;
|
||||
return $cond;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = Mixed;
|
||||
273
node_modules/mongoose/lib/schema/number.js
generated
vendored
Normal file
273
node_modules/mongoose/lib/schema/number.js
generated
vendored
Normal file
@@ -0,0 +1,273 @@
|
||||
/*!
|
||||
* Module requirements.
|
||||
*/
|
||||
|
||||
var SchemaType = require('../schematype')
|
||||
, CastError = SchemaType.CastError
|
||||
, errorMessages = require('../error').messages
|
||||
, utils = require('../utils')
|
||||
, Document
|
||||
|
||||
/**
|
||||
* Number SchemaType constructor.
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function SchemaNumber (key, options) {
|
||||
SchemaType.call(this, key, options, 'Number');
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
SchemaNumber.schemaName = 'Number';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
SchemaNumber.prototype = Object.create( SchemaType.prototype );
|
||||
SchemaNumber.prototype.constructor = SchemaNumber;
|
||||
|
||||
/**
|
||||
* Required validator for number
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaNumber.prototype.checkRequired = function checkRequired (value, doc) {
|
||||
if (SchemaType._isRef(this, value, doc, true)) {
|
||||
return null != value;
|
||||
} else {
|
||||
return typeof value == 'number' || value instanceof Number;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a minimum number validator.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ n: { type: Number, min: 10 })
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ n: 9 })
|
||||
* m.save(function (err) {
|
||||
* console.error(err) // validator error
|
||||
* m.n = 10;
|
||||
* m.save() // success
|
||||
* })
|
||||
*
|
||||
* // custom error messages
|
||||
* // We can also use the special {MIN} token which will be replaced with the invalid value
|
||||
* var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
|
||||
* var schema = new Schema({ n: { type: Number, min: min })
|
||||
* var M = mongoose.model('Measurement', schema);
|
||||
* var s= new M({ n: 4 });
|
||||
* s.validate(function (err) {
|
||||
* console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
|
||||
* })
|
||||
*
|
||||
* @param {Number} value minimum number
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaNumber.prototype.min = function (value, message) {
|
||||
if (this.minValidator) {
|
||||
this.validators = this.validators.filter(function (v) {
|
||||
return v.validator != this.minValidator;
|
||||
}, this);
|
||||
}
|
||||
|
||||
if (null != value) {
|
||||
var msg = message || errorMessages.Number.min;
|
||||
msg = msg.replace(/{MIN}/, value);
|
||||
this.validators.push({
|
||||
validator: this.minValidator = function (v) {
|
||||
return v === null || v >= value;
|
||||
},
|
||||
message: msg,
|
||||
type: 'min'
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a maximum number validator.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ n: { type: Number, max: 10 })
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ n: 11 })
|
||||
* m.save(function (err) {
|
||||
* console.error(err) // validator error
|
||||
* m.n = 10;
|
||||
* m.save() // success
|
||||
* })
|
||||
*
|
||||
* // custom error messages
|
||||
* // We can also use the special {MAX} token which will be replaced with the invalid value
|
||||
* var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
|
||||
* var schema = new Schema({ n: { type: Number, max: max })
|
||||
* var M = mongoose.model('Measurement', schema);
|
||||
* var s= new M({ n: 4 });
|
||||
* s.validate(function (err) {
|
||||
* console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
|
||||
* })
|
||||
*
|
||||
* @param {Number} maximum number
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaNumber.prototype.max = function (value, message) {
|
||||
if (this.maxValidator) {
|
||||
this.validators = this.validators.filter(function(v){
|
||||
return v.validator != this.maxValidator;
|
||||
}, this);
|
||||
}
|
||||
|
||||
if (null != value) {
|
||||
var msg = message || errorMessages.Number.max;
|
||||
msg = msg.replace(/{MAX}/, value);
|
||||
this.validators.push({
|
||||
validator: this.maxValidator = function(v) {
|
||||
return v === null || v <= value;
|
||||
},
|
||||
message: msg,
|
||||
type: 'max'
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts to number
|
||||
*
|
||||
* @param {Object} value value to cast
|
||||
* @param {Document} doc document that triggers the casting
|
||||
* @param {Boolean} init
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaNumber.prototype.cast = function (value, doc, init) {
|
||||
if (SchemaType._isRef(this, value, doc, init)) {
|
||||
// wait! we may need to cast this to a document
|
||||
|
||||
if (null == value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// lazy load
|
||||
Document || (Document = require('./../document'));
|
||||
|
||||
if (value instanceof Document) {
|
||||
value.$__.wasPopulated = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
// setting a populated path
|
||||
if ('number' == typeof value) {
|
||||
return value;
|
||||
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
|
||||
throw new CastError('number', value, this.path);
|
||||
}
|
||||
|
||||
// Handle the case where user directly sets a populated
|
||||
// path to a plain object; cast to the Model used in
|
||||
// the population query.
|
||||
var path = doc.$__fullPath(this.path);
|
||||
var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
var pop = owner.populated(path, true);
|
||||
var ret = new pop.options.model(value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
var val = value && value._id
|
||||
? value._id // documents
|
||||
: value;
|
||||
|
||||
if (!isNaN(val)){
|
||||
if (null === val) return val;
|
||||
if ('' === val) return null;
|
||||
if ('string' == typeof val) val = Number(val);
|
||||
if (val instanceof Number) return val
|
||||
if ('number' == typeof val) return val;
|
||||
if (val.toString && !Array.isArray(val) &&
|
||||
val.toString() == Number(val)) {
|
||||
return new Number(val)
|
||||
}
|
||||
}
|
||||
|
||||
throw new CastError('number', value, this.path);
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function handleSingle (val) {
|
||||
return this.cast(val)
|
||||
}
|
||||
|
||||
function handleArray (val) {
|
||||
var self = this;
|
||||
return val.map(function (m) {
|
||||
return self.cast(m)
|
||||
});
|
||||
}
|
||||
|
||||
SchemaNumber.prototype.$conditionalHandlers =
|
||||
utils.options(SchemaType.prototype.$conditionalHandlers, {
|
||||
'$all': handleArray,
|
||||
'$gt' : handleSingle,
|
||||
'$gte': handleSingle,
|
||||
'$in' : handleArray,
|
||||
'$lt' : handleSingle,
|
||||
'$lte': handleSingle,
|
||||
'$ne' : handleSingle,
|
||||
'$mod': handleArray,
|
||||
'$nin': handleArray
|
||||
});
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} [value]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaNumber.prototype.castForQuery = function ($conditional, val) {
|
||||
var handler;
|
||||
if (arguments.length === 2) {
|
||||
handler = this.$conditionalHandlers[$conditional];
|
||||
if (!handler)
|
||||
throw new Error("Can't use " + $conditional + " with Number.");
|
||||
return handler.call(this, val);
|
||||
} else {
|
||||
val = this.cast($conditional);
|
||||
return val == null ? val : val
|
||||
}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = SchemaNumber;
|
||||
203
node_modules/mongoose/lib/schema/objectid.js
generated
vendored
Normal file
203
node_modules/mongoose/lib/schema/objectid.js
generated
vendored
Normal file
@@ -0,0 +1,203 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var SchemaType = require('../schematype')
|
||||
, CastError = SchemaType.CastError
|
||||
, oid = require('../types/objectid')
|
||||
, utils = require('../utils')
|
||||
, Document
|
||||
|
||||
/**
|
||||
* ObjectId SchemaType constructor.
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function ObjectId (key, options) {
|
||||
SchemaType.call(this, key, options, 'ObjectID');
|
||||
}
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
ObjectId.schemaName = 'ObjectId';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
ObjectId.prototype = Object.create( SchemaType.prototype );
|
||||
ObjectId.prototype.constructor = ObjectId;
|
||||
|
||||
/**
|
||||
* Adds an auto-generated ObjectId default if turnOn is true.
|
||||
* @param {Boolean} turnOn auto generated ObjectId defaults
|
||||
* @api public
|
||||
* @return {SchemaType} this
|
||||
*/
|
||||
|
||||
ObjectId.prototype.auto = function (turnOn) {
|
||||
if (turnOn) {
|
||||
this.default(defaultId);
|
||||
this.set(resetId)
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check required
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
ObjectId.prototype.checkRequired = function checkRequired (value, doc) {
|
||||
if (SchemaType._isRef(this, value, doc, true)) {
|
||||
return null != value;
|
||||
} else {
|
||||
return value instanceof oid;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts to ObjectId
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Object} doc
|
||||
* @param {Boolean} init whether this is an initialization cast
|
||||
* @api private
|
||||
*/
|
||||
|
||||
ObjectId.prototype.cast = function (value, doc, init) {
|
||||
if (SchemaType._isRef(this, value, doc, init)) {
|
||||
// wait! we may need to cast this to a document
|
||||
|
||||
if (null == value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// lazy load
|
||||
Document || (Document = require('./../document'));
|
||||
|
||||
if (value instanceof Document) {
|
||||
value.$__.wasPopulated = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
// setting a populated path
|
||||
if (value instanceof oid) {
|
||||
return value;
|
||||
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
|
||||
throw new CastError('ObjectId', value, this.path);
|
||||
}
|
||||
|
||||
// Handle the case where user directly sets a populated
|
||||
// path to a plain object; cast to the Model used in
|
||||
// the population query.
|
||||
var path = doc.$__fullPath(this.path);
|
||||
var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
var pop = owner.populated(path, true);
|
||||
var ret = new pop.options.model(value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// If null or undefined
|
||||
if (value == null) return value;
|
||||
|
||||
if (value instanceof oid)
|
||||
return value;
|
||||
|
||||
if (value._id) {
|
||||
if (value._id instanceof oid) {
|
||||
return value._id;
|
||||
}
|
||||
if (value._id.toString instanceof Function) {
|
||||
try {
|
||||
return oid.createFromHexString(value._id.toString());
|
||||
} catch(e) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (value.toString instanceof Function) {
|
||||
try {
|
||||
return oid.createFromHexString(value.toString());
|
||||
} catch (err) {
|
||||
throw new CastError('ObjectId', value, this.path);
|
||||
}
|
||||
}
|
||||
|
||||
throw new CastError('ObjectId', value, this.path);
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function handleSingle (val) {
|
||||
return this.cast(val);
|
||||
}
|
||||
|
||||
function handleArray (val) {
|
||||
var self = this;
|
||||
return val.map(function (m) {
|
||||
return self.cast(m);
|
||||
});
|
||||
}
|
||||
|
||||
ObjectId.prototype.$conditionalHandlers =
|
||||
utils.options(SchemaType.prototype.$conditionalHandlers, {
|
||||
'$all': handleArray,
|
||||
'$gt': handleSingle,
|
||||
'$gte': handleSingle,
|
||||
'$in': handleArray,
|
||||
'$lt': handleSingle,
|
||||
'$lte': handleSingle,
|
||||
'$ne': handleSingle,
|
||||
'$nin': handleArray
|
||||
});
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} [val]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
ObjectId.prototype.castForQuery = function ($conditional, val) {
|
||||
var handler;
|
||||
if (arguments.length === 2) {
|
||||
handler = this.$conditionalHandlers[$conditional];
|
||||
if (!handler)
|
||||
throw new Error("Can't use " + $conditional + " with ObjectId.");
|
||||
return handler.call(this, val);
|
||||
} else {
|
||||
return this.cast($conditional);
|
||||
}
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function defaultId () {
|
||||
return new oid();
|
||||
};
|
||||
|
||||
function resetId (v) {
|
||||
this.$__._id = null;
|
||||
return v;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = ObjectId;
|
||||
480
node_modules/mongoose/lib/schema/string.js
generated
vendored
Normal file
480
node_modules/mongoose/lib/schema/string.js
generated
vendored
Normal file
@@ -0,0 +1,480 @@
|
||||
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var SchemaType = require('../schematype')
|
||||
, CastError = SchemaType.CastError
|
||||
, errorMessages = require('../error').messages
|
||||
, utils = require('../utils')
|
||||
, Document
|
||||
|
||||
/**
|
||||
* String SchemaType constructor.
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {Object} options
|
||||
* @inherits SchemaType
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function SchemaString (key, options) {
|
||||
this.enumValues = [];
|
||||
this.regExp = null;
|
||||
SchemaType.call(this, key, options, 'String');
|
||||
};
|
||||
|
||||
/**
|
||||
* This schema type's name, to defend against minifiers that mangle
|
||||
* function names.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
SchemaString.schemaName = 'String';
|
||||
|
||||
/*!
|
||||
* Inherits from SchemaType.
|
||||
*/
|
||||
SchemaString.prototype = Object.create( SchemaType.prototype );
|
||||
SchemaString.prototype.constructor = SchemaString;
|
||||
|
||||
/**
|
||||
* Adds an enum validator
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var states = 'opening open closing closed'.split(' ')
|
||||
* var s = new Schema({ state: { type: String, enum: states }})
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ state: 'invalid' })
|
||||
* m.save(function (err) {
|
||||
* console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
|
||||
* m.state = 'open'
|
||||
* m.save(callback) // success
|
||||
* })
|
||||
*
|
||||
* // or with custom error messages
|
||||
* var enu = {
|
||||
* values: 'opening open closing closed'.split(' '),
|
||||
* message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
|
||||
* }
|
||||
* var s = new Schema({ state: { type: String, enum: enu })
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ state: 'invalid' })
|
||||
* m.save(function (err) {
|
||||
* console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
|
||||
* m.state = 'open'
|
||||
* m.save(callback) // success
|
||||
* })
|
||||
*
|
||||
* @param {String|Object} [args...] enumeration values
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaString.prototype.enum = function () {
|
||||
if (this.enumValidator) {
|
||||
this.validators = this.validators.filter(function(v) {
|
||||
return v.validator != this.enumValidator;
|
||||
}, this);
|
||||
this.enumValidator = false;
|
||||
}
|
||||
|
||||
if (undefined === arguments[0] || false === arguments[0]) {
|
||||
return this;
|
||||
}
|
||||
|
||||
var values;
|
||||
var errorMessage;
|
||||
|
||||
if (utils.isObject(arguments[0])) {
|
||||
values = arguments[0].values;
|
||||
errorMessage = arguments[0].message;
|
||||
} else {
|
||||
values = arguments;
|
||||
errorMessage = errorMessages.String.enum;
|
||||
}
|
||||
|
||||
for (var i = 0; i < values.length; i++) {
|
||||
if (undefined !== values[i]) {
|
||||
this.enumValues.push(this.cast(values[i]));
|
||||
}
|
||||
}
|
||||
|
||||
var vals = this.enumValues;
|
||||
this.enumValidator = function (v) {
|
||||
return undefined === v || ~vals.indexOf(v);
|
||||
};
|
||||
this.validators.push({
|
||||
validator: this.enumValidator,
|
||||
message: errorMessage,
|
||||
type: 'enum'
|
||||
});
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a lowercase setter.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ email: { type: String, lowercase: true }})
|
||||
* var M = db.model('M', s);
|
||||
* var m = new M({ email: 'SomeEmail@example.COM' });
|
||||
* console.log(m.email) // someemail@example.com
|
||||
*
|
||||
* @api public
|
||||
* @return {SchemaType} this
|
||||
*/
|
||||
|
||||
SchemaString.prototype.lowercase = function () {
|
||||
return this.set(function (v, self) {
|
||||
if ('string' != typeof v) v = self.cast(v)
|
||||
if (v) return v.toLowerCase();
|
||||
return v;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds an uppercase setter.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ caps: { type: String, uppercase: true }})
|
||||
* var M = db.model('M', s);
|
||||
* var m = new M({ caps: 'an example' });
|
||||
* console.log(m.caps) // AN EXAMPLE
|
||||
*
|
||||
* @api public
|
||||
* @return {SchemaType} this
|
||||
*/
|
||||
|
||||
SchemaString.prototype.uppercase = function () {
|
||||
return this.set(function (v, self) {
|
||||
if ('string' != typeof v) v = self.cast(v)
|
||||
if (v) return v.toUpperCase();
|
||||
return v;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a trim setter.
|
||||
*
|
||||
* The string value will be trimmed when set.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ name: { type: String, trim: true }})
|
||||
* var M = db.model('M', s)
|
||||
* var string = ' some name '
|
||||
* console.log(string.length) // 11
|
||||
* var m = new M({ name: string })
|
||||
* console.log(m.name.length) // 9
|
||||
*
|
||||
* @api public
|
||||
* @return {SchemaType} this
|
||||
*/
|
||||
|
||||
SchemaString.prototype.trim = function () {
|
||||
return this.set(function (v, self) {
|
||||
if ('string' != typeof v) v = self.cast(v)
|
||||
if (v) return v.trim();
|
||||
return v;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a minimum length validator.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var schema = new Schema({ postalCode: { type: String, minlength: 5 })
|
||||
* var Address = db.model('Address', schema)
|
||||
* var address = new Address({ postalCode: '9512' })
|
||||
* address.save(function (err) {
|
||||
* console.error(err) // validator error
|
||||
* address.postalCode = '95125';
|
||||
* address.save() // success
|
||||
* })
|
||||
*
|
||||
* // custom error messages
|
||||
* // We can also use the special {MINLENGTH} token which will be replaced with the invalid value
|
||||
* var minlength = [10, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum length ({MINLENGTH}).'];
|
||||
* var schema = new Schema({ postalCode: { type: String, minlength: minlength })
|
||||
* var Address = mongoose.model('Address', schema);
|
||||
* var address = new Address({ postalCode: '9512' });
|
||||
* s.validate(function (err) {
|
||||
* console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
|
||||
* })
|
||||
*
|
||||
* @param {Number} value minimum string length
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaString.prototype.minlength = function (value, message) {
|
||||
if (this.minlengthValidator) {
|
||||
this.validators = this.validators.filter(function (v) {
|
||||
return v.validator != this.minlengthValidator;
|
||||
}, this);
|
||||
}
|
||||
|
||||
if (null != value) {
|
||||
var msg = message || errorMessages.String.minlength;
|
||||
msg = msg.replace(/{MINLENGTH}/, value);
|
||||
this.validators.push({
|
||||
validator: this.minlengthValidator = function (v) {
|
||||
return v === null || v.length >= value;
|
||||
},
|
||||
message: msg,
|
||||
type: 'minlength'
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a maximum length validator.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var schema = new Schema({ postalCode: { type: String, maxlength: 9 })
|
||||
* var Address = db.model('Address', schema)
|
||||
* var address = new Address({ postalCode: '9512512345' })
|
||||
* address.save(function (err) {
|
||||
* console.error(err) // validator error
|
||||
* address.postalCode = '95125';
|
||||
* address.save() // success
|
||||
* })
|
||||
*
|
||||
* // custom error messages
|
||||
* // We can also use the special {MAXLENGTH} token which will be replaced with the invalid value
|
||||
* var maxlength = [10, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
|
||||
* var schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
|
||||
* var Address = mongoose.model('Address', schema);
|
||||
* var address = new Address({ postalCode: '9512512345' });
|
||||
* address.validate(function (err) {
|
||||
* console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (10).
|
||||
* })
|
||||
*
|
||||
* @param {Number} value maximum string length
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaString.prototype.maxlength = function (value, message) {
|
||||
if (this.maxlengthValidator) {
|
||||
this.validators = this.validators.filter(function(v){
|
||||
return v.validator != this.maxlengthValidator;
|
||||
}, this);
|
||||
}
|
||||
|
||||
if (null != value) {
|
||||
var msg = message || errorMessages.String.maxlength;
|
||||
msg = msg.replace(/{MAXLENGTH}/, value);
|
||||
this.validators.push({
|
||||
validator: this.maxlengthValidator = function(v) {
|
||||
return v === null || v.length <= value;
|
||||
},
|
||||
message: msg,
|
||||
type: 'maxlength'
|
||||
});
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a regexp validator.
|
||||
*
|
||||
* Any value that does not pass `regExp`.test(val) will fail validation.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ name: { type: String, match: /^a/ }})
|
||||
* var M = db.model('M', s)
|
||||
* var m = new M({ name: 'I am invalid' })
|
||||
* m.validate(function (err) {
|
||||
* console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
|
||||
* m.name = 'apples'
|
||||
* m.validate(function (err) {
|
||||
* assert.ok(err) // success
|
||||
* })
|
||||
* })
|
||||
*
|
||||
* // using a custom error message
|
||||
* var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
|
||||
* var s = new Schema({ file: { type: String, match: match }})
|
||||
* var M = db.model('M', s);
|
||||
* var m = new M({ file: 'invalid' });
|
||||
* m.validate(function (err) {
|
||||
* console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
|
||||
* })
|
||||
*
|
||||
* Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also.
|
||||
*
|
||||
* var s = new Schema({ name: { type: String, match: /^a/, required: true }})
|
||||
*
|
||||
* @param {RegExp} regExp regular expression to test against
|
||||
* @param {String} [message] optional custom error message
|
||||
* @return {SchemaType} this
|
||||
* @see Customized Error Messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaString.prototype.match = function match (regExp, message) {
|
||||
// yes, we allow multiple match validators
|
||||
|
||||
var msg = message || errorMessages.String.match;
|
||||
|
||||
var matchValidator = function(v) {
|
||||
var ret = ((null != v && '' !== v)
|
||||
? regExp.test(v)
|
||||
: true);
|
||||
return ret;
|
||||
};
|
||||
|
||||
this.validators.push({ validator: matchValidator, message: msg, type: 'regexp' });
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check required
|
||||
*
|
||||
* @param {String|null|undefined} value
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaString.prototype.checkRequired = function checkRequired (value, doc) {
|
||||
if (SchemaType._isRef(this, value, doc, true)) {
|
||||
return null != value;
|
||||
} else {
|
||||
return (value instanceof String || typeof value == 'string') && value.length;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Casts to String
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaString.prototype.cast = function (value, doc, init) {
|
||||
if (SchemaType._isRef(this, value, doc, init)) {
|
||||
// wait! we may need to cast this to a document
|
||||
|
||||
if (null == value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// lazy load
|
||||
Document || (Document = require('./../document'));
|
||||
|
||||
if (value instanceof Document) {
|
||||
value.$__.wasPopulated = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
// setting a populated path
|
||||
if ('string' == typeof value) {
|
||||
return value;
|
||||
} else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
|
||||
throw new CastError('string', value, this.path);
|
||||
}
|
||||
|
||||
// Handle the case where user directly sets a populated
|
||||
// path to a plain object; cast to the Model used in
|
||||
// the population query.
|
||||
var path = doc.$__fullPath(this.path);
|
||||
var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
var pop = owner.populated(path, true);
|
||||
var ret = new pop.options.model(value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// If null or undefined
|
||||
if (value == null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if ('undefined' !== typeof value) {
|
||||
// handle documents being passed
|
||||
if (value._id && 'string' == typeof value._id) {
|
||||
return value._id;
|
||||
}
|
||||
|
||||
// Re: gh-647 and gh-3030, we're ok with casting using `toString()`
|
||||
// **unless** its the default Object.toString, because "[object Object]"
|
||||
// doesn't really qualify as useful data
|
||||
if (value.toString && value.toString !== Object.prototype.toString) {
|
||||
return value.toString();
|
||||
}
|
||||
}
|
||||
|
||||
throw new CastError('string', value, this.path);
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function handleSingle (val) {
|
||||
return this.castForQuery(val);
|
||||
}
|
||||
|
||||
function handleArray (val) {
|
||||
var self = this;
|
||||
return val.map(function (m) {
|
||||
return self.castForQuery(m);
|
||||
});
|
||||
}
|
||||
|
||||
SchemaString.prototype.$conditionalHandlers =
|
||||
utils.options(SchemaType.prototype.$conditionalHandlers, {
|
||||
'$all': handleArray,
|
||||
'$gt' : handleSingle,
|
||||
'$gte': handleSingle,
|
||||
'$in' : handleArray,
|
||||
'$lt' : handleSingle,
|
||||
'$lte': handleSingle,
|
||||
'$ne' : handleSingle,
|
||||
'$nin': handleArray,
|
||||
'$options': handleSingle,
|
||||
'$regex': handleSingle
|
||||
});
|
||||
|
||||
/**
|
||||
* Casts contents for queries.
|
||||
*
|
||||
* @param {String} $conditional
|
||||
* @param {any} [val]
|
||||
* @api private
|
||||
*/
|
||||
|
||||
SchemaString.prototype.castForQuery = function ($conditional, val) {
|
||||
var handler;
|
||||
if (arguments.length === 2) {
|
||||
handler = this.$conditionalHandlers[$conditional];
|
||||
if (!handler)
|
||||
throw new Error("Can't use " + $conditional + " with String.");
|
||||
return handler.call(this, val);
|
||||
} else {
|
||||
val = $conditional;
|
||||
if (val instanceof RegExp) return val;
|
||||
return this.cast(val);
|
||||
}
|
||||
};
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = SchemaString;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user