Browse Source

database externa

master
nau 8 years ago
parent
commit
5fa880dd01
616 changed files with 101495 additions and 43736 deletions
  1. +1
    -1
      config.js
  2. +1
    -1
      controllers/userController.js
  3. +19
    -0
      node_modules/jsonwebtoken/CHANGELOG.md
  4. +0
    -2
      node_modules/jsonwebtoken/node_modules/cb/.npmignore
  5. +0
    -6
      node_modules/jsonwebtoken/node_modules/cb/Makefile
  6. +0
    -95
      node_modules/jsonwebtoken/node_modules/cb/README.md
  7. +0
    -39
      node_modules/jsonwebtoken/node_modules/cb/lib/cb.js
  8. +0
    -46
      node_modules/jsonwebtoken/node_modules/cb/package.json
  9. +0
    -125
      node_modules/jsonwebtoken/node_modules/cb/test/tests.js
  10. +2
    -1
      node_modules/jsonwebtoken/node_modules/joi/node_modules/isemail/package.json
  11. +2
    -1
      node_modules/jsonwebtoken/node_modules/joi/node_modules/moment/package.json
  12. +3
    -2
      node_modules/jsonwebtoken/node_modules/joi/node_modules/topo/package.json
  13. +2
    -1
      node_modules/jsonwebtoken/node_modules/joi/package.json
  14. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/camelcase-keys/node_modules/camelcase/package.json
  15. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/camelcase-keys/node_modules/map-obj/package.json
  16. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/camelcase-keys/package.json
  17. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/indent-string/node_modules/get-stdin/package.json
  18. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/indent-string/package.json
  19. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/object-assign/package.json
  20. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/package.json
  21. +2
    -1
      node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/package.json
  22. +3
    -2
      node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/node_modules/buffer-equal-constant-time/package.json
  23. +2
    -1
      node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/node_modules/ecdsa-sig-formatter/node_modules/base64-url/package.json
  24. +2
    -1
      node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/node_modules/ecdsa-sig-formatter/package.json
  25. +2
    -1
      node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/package.json
  26. +2
    -1
      node_modules/jsonwebtoken/node_modules/jws/package.json
  27. +28
    -1
      node_modules/jsonwebtoken/node_modules/lodash.once/LICENSE
  28. +18
    -0
      node_modules/jsonwebtoken/node_modules/lodash.once/README.md
  29. +294
    -0
      node_modules/jsonwebtoken/node_modules/lodash.once/index.js
  30. +78
    -0
      node_modules/jsonwebtoken/node_modules/lodash.once/package.json
  31. +11
    -10
      node_modules/jsonwebtoken/package.json
  32. +2
    -2
      node_modules/jsonwebtoken/sign.js
  33. +3
    -0
      node_modules/mongoose/.eslintignore
  34. +31
    -0
      node_modules/mongoose/.eslintrc.yml
  35. +3
    -0
      node_modules/mongoose/.npmignore
  36. +12
    -5
      node_modules/mongoose/.travis.yml
  37. +23
    -27
      node_modules/mongoose/CONTRIBUTING.md
  38. +1451
    -15
      node_modules/mongoose/History.md
  39. +182
    -130
      node_modules/mongoose/README.md
  40. +13
    -14
      node_modules/mongoose/examples/README.md
  41. +103
    -0
      node_modules/mongoose/examples/aggregate/aggregate.js
  42. +14
    -0
      node_modules/mongoose/examples/aggregate/package.json
  43. +17
    -0
      node_modules/mongoose/examples/aggregate/person.js
  44. +22
    -15
      node_modules/mongoose/examples/doc-methods.js
  45. +1
    -0
      node_modules/mongoose/examples/express/README.md
  46. +6
    -0
      node_modules/mongoose/examples/express/connection-sharing/README.md
  47. +17
    -0
      node_modules/mongoose/examples/express/connection-sharing/app.js
  48. +5
    -0
      node_modules/mongoose/examples/express/connection-sharing/modelA.js
  49. +14
    -0
      node_modules/mongoose/examples/express/connection-sharing/package.json
  50. +20
    -0
      node_modules/mongoose/examples/express/connection-sharing/routes.js
  51. +22
    -0
      node_modules/mongoose/examples/geospatial/geoJSONSchema.js
  52. +56
    -0
      node_modules/mongoose/examples/geospatial/geoJSONexample.js
  53. +100
    -0
      node_modules/mongoose/examples/geospatial/geospatial.js
  54. +14
    -0
      node_modules/mongoose/examples/geospatial/package.json
  55. +27
    -0
      node_modules/mongoose/examples/geospatial/person.js
  56. +47
    -0
      node_modules/mongoose/examples/globalschemas/gs_example.js
  57. +14
    -0
      node_modules/mongoose/examples/globalschemas/person.js
  58. +84
    -0
      node_modules/mongoose/examples/lean/lean.js
  59. +14
    -0
      node_modules/mongoose/examples/lean/package.json
  60. +16
    -0
      node_modules/mongoose/examples/lean/person.js
  61. +100
    -0
      node_modules/mongoose/examples/mapreduce/mapreduce.js
  62. +14
    -0
      node_modules/mongoose/examples/mapreduce/package.json
  63. +16
    -0
      node_modules/mongoose/examples/mapreduce/person.js
  64. +0
    -95
      node_modules/mongoose/examples/population-basic.js
  65. +0
    -101
      node_modules/mongoose/examples/population-of-existing-doc.js
  66. +0
    -112
      node_modules/mongoose/examples/population-of-multiple-existing-docs.js
  67. +0
    -124
      node_modules/mongoose/examples/population-options.js
  68. +0
    -96
      node_modules/mongoose/examples/population-plain-objects.js
  69. +17
    -18
      node_modules/mongoose/examples/population/population-across-three-collections.js
  70. +103
    -0
      node_modules/mongoose/examples/population/population-basic.js
  71. +109
    -0
      node_modules/mongoose/examples/population/population-of-existing-doc.js
  72. +124
    -0
      node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js
  73. +138
    -0
      node_modules/mongoose/examples/population/population-options.js
  74. +106
    -0
      node_modules/mongoose/examples/population/population-plain-objects.js
  75. +14
    -0
      node_modules/mongoose/examples/promises/package.json
  76. +15
    -0
      node_modules/mongoose/examples/promises/person.js
  77. +94
    -0
      node_modules/mongoose/examples/promises/promise.js
  78. +14
    -0
      node_modules/mongoose/examples/querybuilder/package.json
  79. +15
    -0
      node_modules/mongoose/examples/querybuilder/person.js
  80. +79
    -0
      node_modules/mongoose/examples/querybuilder/querybuilder.js
  81. +14
    -0
      node_modules/mongoose/examples/replicasets/package.json
  82. +15
    -0
      node_modules/mongoose/examples/replicasets/person.js
  83. +71
    -0
      node_modules/mongoose/examples/replicasets/replica-sets.js
  84. +0
    -102
      node_modules/mongoose/examples/schema.js
  85. +119
    -0
      node_modules/mongoose/examples/schema/schema.js
  86. +27
    -0
      node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js
  87. +9
    -0
      node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json
  88. +20
    -0
      node_modules/mongoose/examples/statics/person.js
  89. +41
    -0
      node_modules/mongoose/examples/statics/statics.js
  90. +26
    -0
      node_modules/mongoose/lib/ES6Promise.js
  91. +685
    -0
      node_modules/mongoose/lib/aggregate.js
  92. +99
    -0
      node_modules/mongoose/lib/browser.js
  93. +103
    -0
      node_modules/mongoose/lib/browserDocument.js
  94. +238
    -0
      node_modules/mongoose/lib/cast.js
  95. +45
    -27
      node_modules/mongoose/lib/collection.js
  96. +249
    -166
      node_modules/mongoose/lib/connection.js
  97. +3
    -0
      node_modules/mongoose/lib/connectionstate.js
  98. +1377
    -565
      node_modules/mongoose/lib/document.js
  99. +21
    -0
      node_modules/mongoose/lib/document_provider.js
  100. +5
    -0
      node_modules/mongoose/lib/drivers/browser/ReadPreference.js

+ 1
- 1
config.js

@ -1,6 +1,6 @@
module.exports = {
'secret': 'secretfortoken',
'database': 'mongodb://localhost/thoughts'
'database': 'mongodb://userdb:userdb@ds013366.mlab.com:13366/thoughts'
};

+ 1
- 1
controllers/userController.js

@ -53,7 +53,7 @@ exports.findUserByUsername = function(req, res) {
//POST - Insert a new TVShow in the DB
exports.addUser = function(req, res) {
console.log('POST new user, name: ' + req.body.username);
console.log(req.body);
//console.log(req.body);
var user = new userModel({
username: req.body.username,

+ 19
- 0
node_modules/jsonwebtoken/CHANGELOG.md

@ -4,6 +4,25 @@
All notable changes to this project will be documented in this file starting from version **v4.0.0**.
This project adheres to [Semantic Versioning](http://semver.org/).
## 7.1.7 - 2016-07-29
- Use lodash.once instead of unlicensed/unmaintained cb ([3ac95ad93ef3068a64e03d8d14deff231b1ed529](https://github.com/auth0/node-jsonwebtoken/commit/3ac95ad93ef3068a64e03d8d14deff231b1ed529))
## 7.1.6 - 2016-07-15
- fix issue with buffer payload. closes #216 ([6b50ff324b4dfd2cb0e49b666f14a6672d015b22](https://github.com/auth0/node-jsonwebtoken/commit/6b50ff324b4dfd2cb0e49b666f14a6672d015b22)), closes [#216](https://github.com/auth0/node-jsonwebtoken/issues/216)
## 7.1.5 - 2016-07-15
- update jws in package.json ([b6260951eefc68aae5f4ede359210761f901ff7a](https://github.com/auth0/node-jsonwebtoken/commit/b6260951eefc68aae5f4ede359210761f901ff7a))
## 7.1.4 - 2016-07-14
- add redundant test ([bece8816096f324511c3efcb8db0e64b75d757a1](https://github.com/auth0/node-jsonwebtoken/commit/bece8816096f324511c3efcb8db0e64b75d757a1))
- fix an issue of double callback on error ([758ca5eeca2f1b06c32c9fce70642bf488b2e52b](https://github.com/auth0/node-jsonwebtoken/commit/758ca5eeca2f1b06c32c9fce70642bf488b2e52b))
## 7.1.2 - 2016-07-12
- do not stringify the payload when signing async - closes #224 ([084f537d3dfbcef2bea411cc0a1515899cc8aa21](https://github.com/auth0/node-jsonwebtoken/commit/084f537d3dfbcef2bea411cc0a1515899cc8aa21)), closes [#224](https://github.com/auth0/node-jsonwebtoken/issues/224)

+ 0
- 2
node_modules/jsonwebtoken/node_modules/cb/.npmignore

@ -1,2 +0,0 @@
*.DS_Store
node_modules

+ 0
- 6
node_modules/jsonwebtoken/node_modules/cb/Makefile

@ -1,6 +0,0 @@
.PHONY: test
MOCHA = ./node_modules/mocha/bin/mocha
test:
$(MOCHA) -R list

+ 0
- 95
node_modules/jsonwebtoken/node_modules/cb/README.md

@ -1,95 +0,0 @@
# cb()
A minimal node.js utility for handling common (but often overlooked) callback scenarios.
##Features
* `.timeout()`: Simple callback timeouts
* `.error()`: Explicit error handling
* `.once()`: Once-and-only-once callback semantics
* Guaranteed asynchronous callback execution (protects against code that breaks this assumption)
## Installation
$ npm install cb
## Usage
### Basic Usage
The most basic usage of `cb` consists of passing in your own function reference. In this example, `cb` will do nothing other
than insure the once-and-only-once, asynchronous invocation of the callback.
doAsync(cb(function(err, res) {
console.log(res);
}));
### Timeout Handling
Timeouts are specified through the `.timeout()` method, and are specified in milliseconds. If a timeout does occur, the error
passed to the callback will be an instance of `cb.TimeoutError`.
doReallySlowAsync(cb(function(err, res) {
assert(err instanceof cb.TimeoutError);
}).timeout(50));
*Note: once a timeout has occured, any tardy attempts to invoke the callback will be ignored.*
### Explicit Error Handling
In situations where it is convenient to separate the code that runs on success or failure, this can easily be accomplished
with `.error()`. If an 'errback' handler has been provided to `.error()`, then it is assumed that the error-first parameter
to the success handler is no longer required. To illustrate,
doAsync(cb(function(err, res) {
if (err) {
console.error(err);
} else {
console.log(res);
}
}));
Can be rewritten as:
doAsync(cb(console.log).error(console.error));
### Force Once-and-only-once Callback Execution
Sometimes it's necessary to ensure that a callback is invoked once, and no more. Once-and-only-once execution semantics can be
enforced by using `.once()`.
function runTwice(callback) {
process.nextTick(function() {
callback();
callback();
});
}
runTwice(cb(function() {
console.log('I will only run once');
}).once());
*Note: technically, `.once()` simply enforces at-most-once semantics. However, when combined with `.timeout()`, once-and-only-once
is achieved.*
### Combining Features
The `cb` API is fully chainable, and any arrangement of the features is valid. For example:
doAsync(cb(console.log).error(console.error).timeout(50).once());
## Running the Tests
$ make test
## License
The MIT License (MIT)
Copyright (c) 2012 Jeremy Martin
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.

+ 0
- 39
node_modules/jsonwebtoken/node_modules/cb/lib/cb.js

@ -1,39 +0,0 @@
module.exports = function(callback) {
var cb = function() {
if (timedout || (once && count)) return;
count += 1;
tid && clearTimeout(tid);
var args = Array.prototype.slice.call(arguments);
process.nextTick(function() {
if (!errback) return callback.apply(this, args);
args[0] ? errback(args[0]) : callback.apply(this, args.slice(1));
});
}, count = 0, once = false, timedout = false, errback, tid;
cb.timeout = function(ms) {
tid && clearTimeout(tid);
tid = setTimeout(function() {
cb(new TimeoutError(ms));
timedout = true;
}, ms);
return cb;
};
cb.error = function(func) { errback = func; return cb; };
cb.once = function() { once = true; return cb; };
return cb;
};
var TimeoutError = module.exports.TimeoutError = function TimeoutError(ms) {
this.message = 'Specified timeout of ' + ms + 'ms was reached';
Error.captureStackTrace(this, this.constructor);
};
TimeoutError.prototype = new Error;
TimeoutError.prototype.constructor = TimeoutError;
TimeoutError.prototype.name = 'TimeoutError';

+ 0
- 46
node_modules/jsonwebtoken/node_modules/cb/package.json

@ -1,46 +0,0 @@
{
"author": {
"name": "Jeremy Martin",
"email": "jmar777@gmail.com",
"url": "http://twitter.com/jmar777"
},
"name": "cb",
"description": "Super simple callback mechanism with support for timeouts and explicit error handling",
"version": "0.1.0",
"repository": {
"type": "git",
"url": "git://github.com/jmar777/cb.git"
},
"main": "lib/cb.js",
"devDependencies": {
"mocha": ">=0.3.6"
},
"engines": {
"node": ">=0.6.0"
},
"_npmUser": {
"name": "jmar777",
"email": "jmar777@gmail.com"
},
"_id": "cb@0.1.0",
"dependencies": {},
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.0-2",
"_nodeVersion": "v0.6.8",
"_defaultsLoaded": true,
"dist": {
"shasum": "26f7e740f2808facc83cef7b20392e4d881b5203",
"tarball": "https://registry.npmjs.org/cb/-/cb-0.1.0.tgz"
},
"maintainers": [
{
"name": "jmar777",
"email": "jmar777@gmail.com"
}
],
"directories": {},
"_shasum": "26f7e740f2808facc83cef7b20392e4d881b5203",
"_resolved": "https://registry.npmjs.org/cb/-/cb-0.1.0.tgz",
"_from": "cb@>=0.1.0 <0.2.0"
}

+ 0
- 125
node_modules/jsonwebtoken/node_modules/cb/test/tests.js

@ -1,125 +0,0 @@
var assert = require('assert'),
cb = require('../');
function invokeAsync(callback) {
setTimeout(function() {
callback(null, 'foo');
}, 100);
}
function invokeAsyncError(callback) {
setTimeout(function() {
callback(new Error());
}, 100);
}
function invokeAsyncTwice(callback) {
setTimeout(function() {
callback(null, 'foo');
callback(null, 'foo');
}, 100);
}
describe('cb(callback)', function() {
it('should invoke the provided callback', function(done) {
invokeAsync(cb(function(err, res) {
assert.strictEqual(res, 'foo');
done();
}));
});
it('shouldn\'t mess with errors', function(done) {
invokeAsyncError(cb(function(err, res) {
assert(err);
done();
}));
});
it('should allow multiple executions', function(done) {
var count = 0;
invokeAsyncTwice(cb(function(err, res) {
count++;
if (count === 2) done();
}));
});
});
describe('cb(callback).timeout(ms)', function() {
it('should complete successfully within timeout period', function(done) {
invokeAsync(cb(function(err, res) {
assert.strictEqual(res, 'foo');
done();
}).timeout(200));
});
it('should complete with an error after timeout period', function(done) {
invokeAsync(cb(function(err, res) {
assert(err);
done();
}).timeout(50));
});
it('error resulting from a timeout should be instanceof cb.TimeoutError', function(done) {
invokeAsync(cb(function(err, res) {
assert(err instanceof cb.TimeoutError);
done();
}).timeout(50));
});
});
describe('cb(callback).error(errback)', function() {
it('should skip the err argument when invoking callback', function(done) {
invokeAsync(cb(function(res) {
assert.strictEqual(res, 'foo');
done();
}).error(assert.ifError));
});
it('should pass errors to provided errback', function(done) {
invokeAsyncError(cb(function(res) {
throw new Error('should not be invoked');
}).error(function(err) {
assert(err);
done();
}));
});
});
describe('cb(callback).error(errback).timeout(ms)', function() {
it('should skip the err argument when invoking callback', function(done) {
invokeAsync(cb(function(res) {
assert.strictEqual(res, 'foo');
done();
}).error(assert.ifError).timeout(200));
});
it('should pass timeout error to provided errback', function(done) {
invokeAsyncError(cb(function(res) {
throw new Error('should not be invoked');
}).error(function(err) {
assert(err);
done();
}).timeout(50));
});
});
describe('cb(callback).once()', function() {
it('should allow multiple executions', function(done) {
var count = 0;
invokeAsyncTwice(cb(function(err, res) {
count++;
assert.notEqual(count, 2);
setTimeout(done, 100);
}).once());
});
});

+ 2
- 1
node_modules/jsonwebtoken/node_modules/joi/node_modules/isemail/package.json

@ -58,5 +58,6 @@
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/isemail/-/isemail-1.2.0.tgz"
"_resolved": "https://registry.npmjs.org/isemail/-/isemail-1.2.0.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/joi/node_modules/moment/package.json

@ -144,5 +144,6 @@
"tmp": "tmp/moment-2.14.1.tgz_1467614674915_0.32715084473602474"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/moment/-/moment-2.14.1.tgz"
"_resolved": "https://registry.npmjs.org/moment/-/moment-2.14.1.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/joi/node_modules/topo/package.json

@ -4,7 +4,7 @@
"version": "1.1.0",
"repository": {
"type": "git",
"url": "git://github.com/hapijs/topo"
"url": "git://github.com/hapijs/topo.git"
},
"main": "lib/index.js",
"keywords": [
@ -56,5 +56,6 @@
"tarball": "https://registry.npmjs.org/topo/-/topo-1.1.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/topo/-/topo-1.1.0.tgz"
"_resolved": "https://registry.npmjs.org/topo/-/topo-1.1.0.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/joi/package.json

@ -63,5 +63,6 @@
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/joi/-/joi-6.10.1.tgz"
"_resolved": "https://registry.npmjs.org/joi/-/joi-6.10.1.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/camelcase-keys/node_modules/camelcase/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/camelcase"
"url": "git+https://github.com/sindresorhus/camelcase.git"
},
"author": {
"name": "Sindre Sorhus",
@ -63,5 +63,6 @@
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz"
"_resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/camelcase-keys/node_modules/map-obj/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/map-obj"
"url": "git+https://github.com/sindresorhus/map-obj.git"
},
"author": {
"name": "Sindre Sorhus",
@ -61,5 +61,6 @@
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz"
"_resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/camelcase-keys/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/camelcase-keys"
"url": "git+https://github.com/sindresorhus/camelcase-keys.git"
},
"author": {
"name": "Sindre Sorhus",
@ -76,5 +76,6 @@
"tarball": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-1.0.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-1.0.0.tgz"
"_resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-1.0.0.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/indent-string/node_modules/get-stdin/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/get-stdin"
"url": "git+https://github.com/sindresorhus/get-stdin.git"
},
"author": {
"name": "Sindre Sorhus",
@ -59,5 +59,6 @@
"tarball": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz"
"_resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/indent-string/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/indent-string"
"url": "git+https://github.com/sindresorhus/indent-string.git"
},
"author": {
"name": "Sindre Sorhus",
@ -68,5 +68,6 @@
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/indent-string/-/indent-string-1.2.2.tgz"
"_resolved": "https://registry.npmjs.org/indent-string/-/indent-string-1.2.2.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/node_modules/object-assign/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/object-assign"
"url": "git+https://github.com/sindresorhus/object-assign.git"
},
"author": {
"name": "Sindre Sorhus",
@ -62,5 +62,6 @@
"tarball": "https://registry.npmjs.org/object-assign/-/object-assign-1.0.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/object-assign/-/object-assign-1.0.0.tgz"
"_resolved": "https://registry.npmjs.org/object-assign/-/object-assign-1.0.0.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/node_modules/meow/package.json

@ -5,7 +5,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/meow"
"url": "git+https://github.com/sindresorhus/meow.git"
},
"author": {
"name": "Sindre Sorhus",
@ -63,5 +63,6 @@
"tarball": "https://registry.npmjs.org/meow/-/meow-2.0.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/meow/-/meow-2.0.0.tgz"
"_resolved": "https://registry.npmjs.org/meow/-/meow-2.0.0.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/jws/node_modules/base64url/package.json

@ -57,5 +57,6 @@
"tmp": "tmp/base64url-1.0.6.tgz_1455309394658_0.6706331633031368"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/base64url/-/base64url-1.0.6.tgz"
"_resolved": "https://registry.npmjs.org/base64url/-/base64url-1.0.6.tgz",
"readme": "ERROR: No README data found!"
}

+ 3
- 2
node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/node_modules/buffer-equal-constant-time/package.json

@ -8,7 +8,7 @@
},
"repository": {
"type": "git",
"url": "git@github.com:goinstant/buffer-equal-constant-time.git"
"url": "git+ssh://git@github.com/goinstant/buffer-equal-constant-time.git"
},
"keywords": [
"buffer",
@ -47,5 +47,6 @@
],
"directories": {},
"_shasum": "f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819",
"_resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz"
"_resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"homepage": "https://github.com/goinstant/buffer-equal-constant-time#readme"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/node_modules/ecdsa-sig-formatter/node_modules/base64-url/package.json

@ -69,5 +69,6 @@
"tmp": "tmp/base64-url-1.3.2.tgz_1468593630635_0.8208693880587816"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/base64-url/-/base64-url-1.3.2.tgz"
"_resolved": "https://registry.npmjs.org/base64-url/-/base64-url-1.3.2.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/node_modules/ecdsa-sig-formatter/package.json

@ -69,5 +69,6 @@
"tmp": "tmp/ecdsa-sig-formatter-1.0.7.tgz_1466263566774_0.3799667169805616"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.7.tgz"
"_resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.7.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/jws/node_modules/jwa/package.json

@ -70,5 +70,6 @@
"host": "packages-5-east.internal.npmjs.com",
"tmp": "tmp/jwa-1.1.3.tgz_1455809964709_0.6556255409959704"
},
"_resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.3.tgz"
"_resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.3.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 1
node_modules/jsonwebtoken/node_modules/jws/package.json

@ -67,5 +67,6 @@
"host": "packages-6-west.internal.npmjs.com",
"tmp": "tmp/jws-3.1.3.tgz_1455809983684_0.8235816163942218"
},
"_resolved": "https://registry.npmjs.org/jws/-/jws-3.1.3.tgz"
"_resolved": "https://registry.npmjs.org/jws/-/jws-3.1.3.tgz",
"readme": "ERROR: No README data found!"
}

node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE → node_modules/jsonwebtoken/node_modules/lodash.once/LICENSE

@ -1,4 +1,16 @@
Copyright (c) 2008-2011 Pivotal Labs
Copyright jQuery Foundation and other contributors <https://jquery.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@ -18,3 +30,18 @@ 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.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.

+ 18
- 0
node_modules/jsonwebtoken/node_modules/lodash.once/README.md

@ -0,0 +1,18 @@
# lodash.once v4.1.1
The [lodash](https://lodash.com/) method `_.once` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.once
```
In Node.js:
```js
var once = require('lodash.once');
```
See the [documentation](https://lodash.com/docs#once) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.once) for more details.

+ 294
- 0
node_modules/jsonwebtoken/node_modules/lodash.once/index.js

@ -0,0 +1,294 @@
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = once;

+ 78
- 0
node_modules/jsonwebtoken/node_modules/lodash.once/package.json

@ -0,0 +1,78 @@
{
"name": "lodash.once",
"version": "4.1.1",
"description": "The lodash method `_.once` exported as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"keywords": [
"lodash-modularized",
"once"
],
"author": {
"name": "John-David Dalton",
"email": "john.david.dalton@gmail.com",
"url": "http://allyoucanleet.com/"
},
"contributors": [
{
"name": "John-David Dalton",
"email": "john.david.dalton@gmail.com",
"url": "http://allyoucanleet.com/"
},
{
"name": "Blaine Bublitz",
"email": "blaine.bublitz@gmail.com",
"url": "https://github.com/phated"
},
{
"name": "Mathias Bynens",
"email": "mathias@qiwi.be",
"url": "https://mathiasbynens.be/"
}
],
"repository": {
"type": "git",
"url": "git+https://github.com/lodash/lodash.git"
},
"scripts": {
"test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\""
},
"bugs": {
"url": "https://github.com/lodash/lodash/issues"
},
"_id": "lodash.once@4.1.1",
"_shasum": "0dd3971213c7c56df880977d504c88fb471a97ac",
"_from": "lodash.once@>=4.0.0 <5.0.0",
"_npmVersion": "2.15.10",
"_nodeVersion": "4.4.7",
"_npmUser": {
"name": "jdalton",
"email": "john.david.dalton@gmail.com"
},
"dist": {
"shasum": "0dd3971213c7c56df880977d504c88fb471a97ac",
"tarball": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz"
},
"maintainers": [
{
"name": "jdalton",
"email": "john.david.dalton@gmail.com"
},
{
"name": "mathias",
"email": "mathias@qiwi.be"
},
{
"name": "phated",
"email": "blaine@iceddev.com"
}
],
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/lodash.once-4.1.1.tgz_1471110166870_0.09848929662257433"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"readme": "ERROR: No README data found!"
}

+ 11
- 10
node_modules/jsonwebtoken/package.json

@ -1,6 +1,6 @@
{
"name": "jsonwebtoken",
"version": "7.1.6",
"version": "7.1.9",
"description": "JSON Web Token implementation (symmetric and asymmetric)",
"main": "index.js",
"scripts": {
@ -21,9 +21,9 @@
"url": "https://github.com/auth0/node-jsonwebtoken/issues"
},
"dependencies": {
"cb": "^0.1.0",
"joi": "^6.10.1",
"jws": "^3.1.3",
"lodash.once": "^4.0.0",
"ms": "^0.7.1",
"xtend": "^4.0.1"
},
@ -38,10 +38,10 @@
"npm": ">=1.4.28",
"node": ">=0.12"
},
"gitHead": "ae360b56792a875e16cefa8ff4103b87b4a2e386",
"gitHead": "cc0f4d67b649110a035db3df9265f05db269a15a",
"homepage": "https://github.com/auth0/node-jsonwebtoken#readme",
"_id": "jsonwebtoken@7.1.6",
"_shasum": "2ea9557af144311148f53093cfeec69e1e048abc",
"_id": "jsonwebtoken@7.1.9",
"_shasum": "847804e5258bec5a9499a8dc4a5e7a3bae08d58a",
"_from": "jsonwebtoken@latest",
"_npmVersion": "2.15.1",
"_nodeVersion": "4.4.3",
@ -50,8 +50,8 @@
"email": "jfromaniello@gmail.com"
},
"dist": {
"shasum": "2ea9557af144311148f53093cfeec69e1e048abc",
"tarball": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-7.1.6.tgz"
"shasum": "847804e5258bec5a9499a8dc4a5e7a3bae08d58a",
"tarball": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-7.1.9.tgz"
},
"maintainers": [
{
@ -84,9 +84,10 @@
}
],
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/jsonwebtoken-7.1.6.tgz_1468585972042_0.5801840056665242"
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/jsonwebtoken-7.1.9.tgz_1470932603683_0.2585906428284943"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-7.1.6.tgz"
"_resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-7.1.9.tgz",
"readme": "ERROR: No README data found!"
}

+ 2
- 2
node_modules/jsonwebtoken/sign.js

@ -2,7 +2,7 @@ var Joi = require('joi');
var timespan = require('./lib/timespan');
var xtend = require('xtend');
var jws = require('jws');
var cb = require('cb');
var once = require('lodash.once');
var sign_options_schema = Joi.object().keys({
expiresIn: [Joi.number().integer(), Joi.string()],
@ -129,7 +129,7 @@ module.exports = function (payload, secretOrPrivateKey, options, callback) {
var encoding = options.encoding || 'utf8';
if (typeof callback === 'function') {
callback = callback && cb(callback).once();
callback = callback && once(callback);
jws.createSign({
header: header,

+ 3
- 0
node_modules/mongoose/.eslintignore

@ -0,0 +1,3 @@
docs/
bin/
test/triage/

+ 31
- 0
node_modules/mongoose/.eslintrc.yml

@ -0,0 +1,31 @@
extends: 'eslint:recommended'
env:
node: true
mocha: true
rules:
comma-style: error
consistent-this:
- error
- _this
indent:
- error
- 2
- SwitchCase: 1
VariableDeclarator: 2
keyword-spacing: error
no-console: off
no-multi-spaces: error
no-spaced-func: error
no-trailing-spaces: error
quotes:
- error
- single
semi: error
space-before-blocks: error
space-before-function-paren:
- error
- never
space-infix-ops: error
space-unary-ops: error

+ 3
- 0
node_modules/mongoose/.npmignore

@ -11,3 +11,6 @@ Makefile
CNAME
index.html
index.jade
bin/
karma.*.js
format_deps.js

+ 12
- 5
node_modules/mongoose/.travis.yml

@ -1,7 +1,14 @@
language: node_js
sudo: false
node_js:
- 0.6
- 0.8
- 0.10
services:
- mongodb
- "6"
- "5"
- "4"
- "0.12"
- "0.10"
- "iojs"
before_script:
- wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.11.tgz
- tar -zxvf mongodb-linux-x86_64-2.6.11.tgz
- mkdir -p ./data/db
- ./mongodb-linux-x86_64-2.6.11/bin/mongod --fork --nopreallocj --dbpath ./data/db --syslog --port 27017

+ 23
- 27
node_modules/mongoose/CONTRIBUTING.md

@ -1,60 +1,56 @@
## Contributing to Mongoose
### STOP!
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.
If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), or on [Gitter](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
### 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.
- Before opening a new issue, look for existing [issues](https://github.com/Automattic/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/Automattic/mongoose/issues/new).
- Please post any relevant code samples, preferably a standalone script that
reproduces your issue. Do **not** describe your issue in prose, show your
code.
- If the bug involves an error, please post the stack trace.
- Please post the version of mongoose and mongodb that you're using.
- Please write bug reports in JavaScript (ES5 or ES2015), not coffeescript, typescript, etc.
### 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.
- _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/Automattic/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
- inline documentation for new methods, class members, etc.
- 1 space between conditionals, no space before function parenthesis
- `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).
- `function(err) {`
- Write tests and make sure they pass (tests are in the [test](https://github.com/Automattic/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="..."
- start a mongodb instance on port 27017 if one isn't running already. `mongod --dbpath <path to store data> --port 27017`
- execute `npm test` to run the tests (we're using [mocha](http://mochajs.org/))
- or to execute a single test `npm test -- -g 'some regexp that matches the test description'`
- any mocha flags can be specified with `-- <mocha flags here>`
- For example, you can use `npm test -- -R spec` to use the spec reporter, rather than the dot reporter (by default, the test output looks like a bunch of dots)
### 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 [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/Automattic/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.
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/Automattic/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 master branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from master, and builds all the static pages for you. Now execute `node server.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 master branch with your changes.
If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from the master 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 master 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).
The [plugins](http://plugins.mongoosejs.io/) site is also an [open source project](https://github.com/vkarpov15/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well!

+ 1451
- 15
node_modules/mongoose/History.md
File diff suppressed because it is too large
View File


+ 182
- 130
node_modules/mongoose/README.md

@ -1,69 +1,84 @@
## What's Mongoose?
# Mongoose
Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
[![Build Status](https://api.travis-ci.org/Automattic/mongoose.svg?branch=master)](https://travis-ci.org/Automattic/mongoose)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
[![Dependency Status](https://gemnasium.com/Automattic/mongoose.svg)](https://gemnasium.com/Automattic/mongoose)
## Documentation
[mongoosejs.com](http://mongoosejs.com/)
## Try it live
<a href="https://runnable.com/#learnboost/mongoose/code.js/launch" target="_blank"><img src="https://runnable.com/external/styles/assets/runnablebtn.png" style="width:67px;height:25px;"></a>
## Support
- [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
- [bug reports](https://github.com/learnboost/mongoose/issues/)
- [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
- [MongoDB support](https://docs.mongodb.org/manual/support/)
- [Mongoose Slack Channel](https://mongoosejs.slack.com/)
## Installation
## Plugins
First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads).
Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community.
$ npm install mongoose
Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin).
## Plugins
## Contributors
Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community.
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!
## Contributors
## Live Examples
<a href="http://code.runnable.com/mongoose" target="_blank"><img src="http://i.imgur.com/4yNYDLI.png"></a>
## Installation
First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then:
View all 90+ [contributors](https://github.com/learnboost/mongoose/graphs/contributors).
```sh
$ npm install mongoose
```
## Get Involved
## Stability
Stand up and be counted as a [contributor](https://github.com/LearnBoost/mongoose/blob/master/CONTRIBUTING.md) too!
The current stable branch is [master](https://github.com/Automattic/mongoose/tree/master). The [3.8.x](https://github.com/Automattic/mongoose/tree/3.8.x) branch contains legacy support for the 3.x release series, which is no longer under active development as of September 2015. The [3.8.x docs](http://mongoosejs.com/docs/3.8.x/) are still available.
## Overview
### Connecting to MongoDB
First, we need to define a connection. If your app uses only one database, you should use `mongose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
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`.
var mongoose = require('mongoose');
```js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
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.
Models are defined through the `Schema` interface.
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
```js
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
});
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:
@ -80,24 +95,26 @@ Aside from defining the structure of your documents and the types of data you're
The following example shows some of these features:
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();
});
```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.
@ -105,77 +122,102 @@ Take a look at the example in `examples/schema.js` for an end-to-end example of
Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
var myModel = mongoose.model('ModelName');
```js
var myModel = mongoose.model('ModelName');
```
Or just do it all at once
var MyModel = mongoose.model('ModelName', mySchema);
```js
var MyModel = mongoose.model('ModelName', mySchema);
```
We can then instantiate it, and save it:
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
var instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
//
});
```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
MyModel.find({}, function (err, docs) {
// docs.forEach
});
```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:
var conn = mongoose.createConnection('your connection string');
var MyModel = conn.model('ModelName', schema);
var m = new MyModel;
m.save() // works
```js
var conn = mongoose.createConnection('your connection string'),
MyModel = conn.model('ModelName', schema),
m = new MyModel;
m.save(); // works
```
vs
vs
var conn = mongoose.createConnection('your connection string');
var MyModel = mongoose.model('ModelName', schema);
var m = new MyModel;
m.save() // does not work b/c the default connection object was never connected
```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]
```
comments: [Comment]
```
Where `Comments` is a `Schema` we created. This means that creating embedded documents is as simple as:
Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as:
// retrieve my model
var BlogPost = mongoose.model('BlogPost');
```js
// retrieve my model
var BlogPost = mongoose.model('BlogPost');
// create a blog post
var post = new BlogPost();
// create a blog post
var post = new BlogPost();
// create a comment
post.comments.push({ title: 'My comment' });
// create a comment
post.comments.push({ title: 'My comment' });
post.save(function (err) {
if (!err) console.log('Success!');
});
post.save(function (err) {
if (!err) console.log('Success!');
});
```
The same goes for removing them:
BlogPost.findById(myId, function (err, post) {
if (!err) {
post.comments[0].remove();
post.save(function (err) {
// do something
});
}
```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
@ -187,63 +229,73 @@ 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:
schema.pre('set', function (next, path, val, typel) {
// `this` is the current Document
this.emit('set', path, val);
```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();
});
// 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`:
.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();
})
```js
.pre(method, function firstPre (next, methodArg1, methodArg2) {
// Mutate methodArg1
next("altered-" + methodArg1.toString(), methodArg2);
});
#### Schema gotcha
// pre declaration is chainable
.pre(method, function secondPre (next, methodArg1, methodArg2) {
console.log(methodArg1);
// => 'altered-originalValOfMethodArg1'
`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:
console.log(methodArg2);
// => 'originalValOfMethodArg2'
new Schema({
broken: { type: Boolean }
, asset : {
name: String
, type: String // uh oh, it broke. asset will be interpreted as String
}
});
// 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();
});
```
new Schema({
works: { type: Boolean }
, asset : {
name: String
, type: { type: String } // works. asset is an object with a type property
}
});
#### Schema gotcha
### Driver access
`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:
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.
```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
Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one
notable exception that `YourModel.collection` still buffers
commands. As such, `YourModel.collection.find()` will **not**
return a cursor.
## API Docs
Find the API docs [here](http://mongoosejs.com/docs/api.html), generated by [dox](http://github.com/visionmedia/dox).
Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox)
and [acquit](https://github.com/vkarpov15/acquit).
## License

+ 13
- 14
node_modules/mongoose/examples/README.md

@ -1,40 +1,39 @@
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
- storing schemas as json
- lean querires
- statics
- ~~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
- express + mongoose
- ~~querybuilder~~
- ~~promises~~
- accessing driver collection, db
- connecting to replica sets
- ~~connecting to replica sets~~
- connecting to sharded clusters
- enabling a fail fast mode
- on the fly schemas
- storing files
- map reduce
- aggregation
- ~~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)
- ~~group by (use aggregation)~~
- authentication
- schema migration techniques
- converting documents to plain objects (show transforms)

+ 103
- 0
node_modules/mongoose/examples/aggregate/aggregate.js

@ -0,0 +1,103 @@
// 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) {
if (err) {
// handle error
}
// 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
- 0
node_modules/mongoose/examples/aggregate/package.json

@ -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
- 0
node_modules/mongoose/examples/aggregate/person.js

@ -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);
};

+ 22
- 15
node_modules/mongoose/examples/doc-methods.js

@ -1,5 +1,5 @@
var mongoose = require('mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
@ -9,17 +9,24 @@ console.log('Running mongoose version %s', mongoose.version);
*/
var CharacterSchema = Schema({
name: { type: String, required: true }
, health: { type: Number, min: 0, max: 100 }
})
name: {
type: String,
required: true
},
health: {
type: Number,
min: 0,
max: 100
}
});
/**
* Methods
*/
CharacterSchema.methods.attack = function () {
CharacterSchema.methods.attack = function() {
console.log('%s is attacking', this.name);
}
};
/**
* Character model
@ -32,39 +39,39 @@ var Character = mongoose.model('Character', CharacterSchema);
* the default port (27017)
*/
var dbname = 'mongoose-example-doc-methods-' + ((Math.random()*10000)|0);
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) {
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) {
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) {
function done(err) {
if (err) console.error(err);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.db.dropDatabase(function() {
mongoose.disconnect();
})
});
}

+ 1
- 0
node_modules/mongoose/examples/express/README.md

@ -0,0 +1 @@
Mongoose + Express examples

+ 6
- 0
node_modules/mongoose/examples/express/connection-sharing/README.md

@ -0,0 +1,6 @@
To run:
- Execute `npm install` from this directory
- Execute `node app.js`
- Navigate to `localhost:8000`

+ 17
- 0
node_modules/mongoose/examples/express/connection-sharing/app.js

@ -0,0 +1,17 @@
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');
});

+ 5
- 0
node_modules/mongoose/examples/express/connection-sharing/modelA.js

@ -0,0 +1,5 @@
var Schema = require('../../../lib').Schema;
var mySchema = Schema({name: String});
/* global db */
module.exports = db.model('MyModel', mySchema);

+ 14
- 0
node_modules/mongoose/examples/express/connection-sharing/package.json

@ -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
- 0
node_modules/mongoose/examples/express/connection-sharing/routes.js

@ -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
- 0
node_modules/mongoose/examples/geospatial/geoJSONSchema.js

@ -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);
};

+ 56
- 0
node_modules/mongoose/examples/geospatial/geoJSONexample.js

@ -0,0 +1,56 @@
// 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();
});
}

+ 100
- 0
node_modules/mongoose/examples/geospatial/geospatial.js

@ -0,0 +1,100 @@
// 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) {
if (err) {
// handler error
}
// 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
- 0
node_modules/mongoose/examples/geospatial/package.json

@ -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"
}

+ 27
- 0
node_modules/mongoose/examples/geospatial/person.js

@ -0,0 +1,27 @@
// 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);
};

+ 47
- 0
node_modules/mongoose/examples/globalschemas/gs_example.js

@ -0,0 +1,47 @@
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();
});
}

+ 14
- 0
node_modules/mongoose/examples/globalschemas/person.js

@ -0,0 +1,14 @@
// 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);
};

+ 84
- 0
node_modules/mongoose/examples/lean/lean.js

@ -0,0 +1,84 @@
// 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) {
if (err) {
// handle error
}
// 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
- 0
node_modules/mongoose/examples/lean/package.json

@ -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"
}

+ 16
- 0
node_modules/mongoose/examples/lean/person.js

@ -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,
likes: [String]
});
mongoose.model('Person', PersonSchema);
};

+ 100
- 0
node_modules/mongoose/examples/mapreduce/mapreduce.js

@ -0,0 +1,100 @@
// 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) {
if (err) {
// handle error
}
// 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
/* global 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
- 0
node_modules/mongoose/examples/mapreduce/package.json

@ -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
- 0
node_modules/mongoose/examples/mapreduce/person.js

@ -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);
};

+ 0
- 95
node_modules/mongoose/examples/population-basic.js

@ -1,95 +0,0 @@
var mongoose = require('mongoose')
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();
})
})
}

+ 0
- 101
node_modules/mongoose/examples/population-of-existing-doc.js

@ -1,101 +0,0 @@
var mongoose = require('mongoose')
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();
})
})
}

+ 0
- 112
node_modules/mongoose/examples/population-of-multiple-existing-docs.js

@ -1,112 +0,0 @@
var mongoose = require('mongoose')
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();
})
})
}

+ 0
- 124
node_modules/mongoose/examples/population-options.js

@ -1,124 +0,0 @@
var mongoose = require('mongoose')
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();
})
})
}

+ 0
- 96
node_modules/mongoose/examples/population-plain-objects.js

@ -1,96 +0,0 @@
var mongoose = require('mongoose')
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();
})
})
}

node_modules/mongoose/examples/population-across-three-collections.js → node_modules/mongoose/examples/population/population-across-three-collections.js

@ -1,6 +1,6 @@
var assert = require('assert')
var mongoose = require('../');
var assert = require('assert');
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Types.ObjectId;
@ -8,7 +8,7 @@ var ObjectId = mongoose.Types.ObjectId;
* Connect to the db
*/
var dbname = 'testing_populateAdInfinitum_' + require('../lib/utils').random()
var dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random();
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function() {
console.error('connection error', arguments);
@ -34,7 +34,7 @@ var blogpost = Schema({
type: Schema.ObjectId,
ref: 'User'
}
})
});
var BlogPost = mongoose.model('BlogPost', blogpost);
/**
@ -42,7 +42,6 @@ var BlogPost = mongoose.model('BlogPost', blogpost);
*/
mongoose.connection.on('open', function() {
/**
* Generate data
*/
@ -71,7 +70,7 @@ mongoose.connection.on('open', function() {
friends: [userIds[0], userIds[1], userIds[2]]
});
User.create(users, function(err, docs) {
User.create(users, function(err) {
assert.ifError(err);
var blogposts = [];
@ -79,19 +78,19 @@ mongoose.connection.on('open', function() {
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) {
BlogPost.create(blogposts, function(err) {
assert.ifError(err);
/**
@ -99,7 +98,7 @@ mongoose.connection.on('open', function() {
*/
BlogPost
.find({ tags: 'fun' })
.find({tags: 'fun'})
.lean()
.populate('author')
.exec(function(err, docs) {
@ -112,19 +111,19 @@ mongoose.connection.on('open', function() {
var opts = {
path: 'author.friends',
select: 'name',
options: { limit: 2 }
}
options: {limit: 2}
};
BlogPost.populate(docs, opts, function(err, docs) {
assert.ifError(err);
console.log('populated');
var s = require('util').inspect(docs, { depth: null })
var s = require('util').inspect(docs, {depth: null, colors: true});
console.log(s);
done();
})
})
})
})
});
});
});
});
});
function done(err) {

+ 103
- 0
node_modules/mongoose/examples/population/population-basic.js

@ -0,0 +1,103 @@
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();
});
});
}

+ 109
- 0
node_modules/mongoose/examples/population/population-of-existing-doc.js

@ -0,0 +1,109 @@
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();
});
});
}

+ 124
- 0
node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js

@ -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'
},
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();
});
});
}

+ 138
- 0
node_modules/mongoose/examples/population/population-options.js

@ -0,0 +1,138 @@
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();
});
});
}

+ 106
- 0
node_modules/mongoose/examples/population/population-plain-objects.js

@ -0,0 +1,106 @@
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
- 0
node_modules/mongoose/examples/promises/package.json

@ -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
- 0
node_modules/mongoose/examples/promises/person.js

@ -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);
};

+ 94
- 0
node_modules/mongoose/examples/promises/promise.js

@ -0,0 +1,94 @@
// 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) {
// handle error
}
// 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
- 0
node_modules/mongoose/examples/querybuilder/package.json

@ -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
- 0
node_modules/mongoose/examples/querybuilder/person.js

@ -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);
};

+ 79
- 0
node_modules/mongoose/examples/querybuilder/querybuilder.js

@ -0,0 +1,79 @@
// 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
- 0
node_modules/mongoose/examples/replicasets/package.json

@ -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
- 0
node_modules/mongoose/examples/replicasets/person.js

@ -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);
};

+ 71
- 0
node_modules/mongoose/examples/replicasets/replica-sets.js

@ -0,0 +1,71 @@
// 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) {
if (err) {
// handle error
}
// 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();
});
}

+ 0
- 102
node_modules/mongoose/examples/schema.js

@ -1,102 +0,0 @@
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, 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);

+ 119
- 0
node_modules/mongoose/examples/schema/schema.js

@ -0,0 +1,119 @@
/**
* 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) {
/* global emailAuthor */
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
- 0
node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js

@ -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
- 0
node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json

@ -0,0 +1,9 @@
{
"count": "number",
"unit": "number",
"description": "string",
"links": ["string"],
"created": "date",
"additive": "boolean",
"user_id": "ObjectId"
}

+ 20
- 0
node_modules/mongoose/examples/statics/person.js

@ -0,0 +1,20 @@
// 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);
};

+ 41
- 0
node_modules/mongoose/examples/statics/statics.js

@ -0,0 +1,41 @@
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();
});
}

+ 26
- 0
node_modules/mongoose/lib/ES6Promise.js

@ -0,0 +1,26 @@
/**
* ES6 Promise wrapper constructor.
*
* Promises are returned from executed queries. Example:
*
* var query = Candy.find({ bar: true });
* var promise = query.exec();
*
* DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird,
* if native promises are not present) but still
* support plugging in your own ES6-compatible promises library. Mongoose 5.0
* will **not** support mpromise.
*
* @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature
* @api public
*/
function ES6Promise() {
throw new Error('Can\'t use ES6 promise with mpromise style constructor');
}
ES6Promise.use = function(Promise) {
ES6Promise.ES6 = Promise;
};
module.exports = ES6Promise;

+ 685
- 0
node_modules/mongoose/lib/aggregate.js

@ -0,0 +1,685 @@
/*!
* Module dependencies
*/
var util = require('util');
var utils = require('./utils');
var PromiseProvider = require('./promise_provider');
var Query = require('./query');
var 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
* - Mongoose does **not** cast pipeline stages. `new Aggregate({ $match: { _id: '00000000000000000000000a' } });` will not work unless `_id` is a string in the database. Use `new Aggregate({ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } });` instead.
*
* @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 (arguments.length === 1 && 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 public
*/
Aggregate.prototype.model = 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 = (arguments.length === 1 && util.isArray(arguments[0]))
? arguments[0]
: utils.args(arguments);
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 (typeof arg === 'object' && !util.isArray(arg)) {
Object.keys(arg).forEach(function(field) {
fields[field] = arg[field];
});
} else if (arguments.length === 1 && typeof arg === 'string') {
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.
*
* Note that the `$unwind` operator requires the path name to start with '$'.
* Mongoose will prepend '$' if the specified field doesn't start '$'.
*
* ####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);
var res = [];
for (var i = 0; i < args.length; ++i) {
var arg = args[i];
if (arg && typeof arg === 'object') {
res.push({ $unwind: arg });
} else if (typeof arg === 'string') {
res.push({
$unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg
});
} else {
throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
'must be string or object');
}
}
return this.append.apply(this, res);
};
/**
* Appends new custom $lookup operator(s) to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
*
* @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup
* @param {Object} options to $lookup as described in the above link
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.lookup = function(options) {
return this.append({$lookup: options});
};
/**
* Appends new custom $sample operator(s) to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.sample(3); // Add a pipeline that picks 3 random documents
*
* @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample
* @param {Number} size number of random documents to pick
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.sample = function(size) {
return this.append({$sample: {size: size}});
};
/**
* 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 (arg.constructor.name === 'Object') {
var desc = ['desc', 'descending', -1];
Object.keys(arg).forEach(function(field) {
sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
});
} else if (arguments.length === 1 && typeof arg === 'string') {
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, tags) {
if (!this.options) {
this.options = {};
}
read.call(this, pref, tags);
return this;
};
/**
* Execute the aggregation with explain
*
* ####Example:
*
* Model.aggregate(..).explain(callback)
*
* @param {Function} callback
* @return {Promise}
*/
Aggregate.prototype.explain = function(callback) {
var _this = this;
var Promise = PromiseProvider.get();
return new Promise.ES6(function(resolve, reject) {
if (!_this._pipeline.length) {
var err = new Error('Aggregate has empty pipeline');
if (callback) {
callback(err);
}
reject(err);
return;
}
prepareDiscriminatorPipeline(_this);
_this._model
.collection
.aggregate(_this._pipeline, _this.options || {})
.explain(function(error, result) {
if (error) {
if (callback) {
callback(error);
}
reject(error);
return;
}
if (callback) {
callback(null, result);
}
resolve(result);
});
});
};
/**
* 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;
};
/**
* Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addCursorFlag)
*
* ####Example:
*
* var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
* cursor.each(function(error, doc) {
* // use doc
* });
*
* @param {String} flag
* @param {Boolean} value
* @see mongodb http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addCursorFlag
*/
Aggregate.prototype.addCursorFlag = function(flag, value) {
if (!this.options) {
this.options = {};
}
this.options[flag] = value;
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) {
if (!this._model) {
throw new Error('Aggregate not bound to any Model');
}
var _this = this;
var Promise = PromiseProvider.get();
var options = utils.clone(this.options);
if (options && options.cursor) {
if (options.cursor.async) {
delete options.cursor.async;
return new Promise.ES6(function(resolve) {
if (!_this._model.collection.buffer) {
process.nextTick(function() {
var cursor = _this._model.collection.
aggregate(_this._pipeline, options || {});
resolve(cursor);
callback && callback(null, cursor);
});
return;
}
_this._model.collection.emitter.once('queue', function() {
var cursor = _this._model.collection.
aggregate(_this._pipeline, options || {});
resolve(cursor);
callback && callback(null, cursor);
});
});
}
return this._model.collection.
aggregate(this._pipeline, this.options || {});
}
return new Promise.ES6(function(resolve, reject) {
if (!_this._pipeline.length) {
var err = new Error('Aggregate has empty pipeline');
if (callback) {
callback(err);
}
reject(err);
return;
}
prepareDiscriminatorPipeline(_this);
_this._model
.collection
.aggregate(_this._pipeline, _this.options || {}, function(error, result) {
if (error) {
if (callback) {
callback(error);
}
reject(error);
return;
}
if (callback) {
callback(null, result);
}
resolve(result);
});
});
};
/**
* Provides promise for aggregate.
*
* ####Example:
*
* Model.aggregate(..).then(successCallback, errorCallback);
*
* @see Promise #promise_Promise
* @param {Function} [resolve] successCallback
* @param {Function} [reject] errorCallback
* @return {Promise}
*/
Aggregate.prototype.then = function(resolve, reject) {
var _this = this;
var Promise = PromiseProvider.get();
var promise = new Promise.ES6(function(success, error) {
_this.exec(function(err, val) {
if (err) error(err);
else success(val);
});
});
return promise.then(resolve, reject);
};
/*!
* 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 (typeof obj !== 'object') {
return false;
}
k = Object.keys(obj);
return k.length === 1 && 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 if (originalPipeline[0] && originalPipeline[0].$geoNear) {
originalPipeline[0].$geoNear.query =
originalPipeline[0].$geoNear.query || {};
originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue;
} else {
var match = {};
match[discriminatorKey] = discriminatorValue;
aggregate._pipeline = [{$match: match}].concat(originalPipeline);
}
}
}
/*!
* Exports
*/
module.exports = Aggregate;

+ 99
- 0
node_modules/mongoose/lib/browser.js

@ -0,0 +1,99 @@
/* eslint-env browser */
/**
* 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;
}

+ 103
- 0
node_modules/mongoose/lib/browserDocument.js

@ -0,0 +1,103 @@
/*!
* Module dependencies.
*/
var NodeJSDocument = require('./document'),
EventEmitter = require('events').EventEmitter,
MongooseError = require('./error'),
Schema = require('./schema'),
ObjectId = require('./types/objectid'),
utils = require('./utils'),
ValidationError = MongooseError.ValidationError,
InternalCache = require('./internal');
/**
* 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 retrieved 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.instanceOfSchema) {
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 (typeof fields === 'boolean') {
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]);
}
this.$__.emitter.setMaxListeners(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;

+ 238
- 0
node_modules/mongoose/lib/cast.js

@ -0,0 +1,238 @@
/*!
* Module dependencies.
*/
var utils = require('./utils');
var Types = require('./schema/index');
var ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
/**
* Handles internal casting for queries
*
* @param {Schema} schema
* @param {Object} obj Object to cast
* @api private
*/
module.exports = function cast(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 (path === '$or' || path === '$nor' || path === '$and') {
var k = val.length;
while (k--) {
val[k] = cast(schema, val[k]);
}
} else if (path === '$where') {
type = typeof val;
if (type !== 'string' && type !== 'function') {
throw new Error('Must have a string or function for $where');
}
if (type === 'function') {
obj[path] = val.toString();
}
continue;
} else if (path === '$elemMatch') {
val = cast(schema, val);
} 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;
// 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 = '';
if (val.$near) {
geo = '$near';
} else if (val.$nearSphere) {
geo = '$nearSphere';
} else if (val.$within) {
geo = '$within';
} else if (val.$geoIntersects) {
geo = '$geoIntersects';
} else if (val.$geoWithin) {
geo = '$geoWithin';
}
if (!geo) {
continue;
}
var numbertype = new Types.Number('__QueryCasting__');
var value = val[geo];
if (val.$maxDistance != null) {
val.$maxDistance = numbertype.castForQuery(val.$maxDistance);
}
if (val.$minDistance != null) {
val.$minDistance = numbertype.castForQuery(val.$minDistance);
}
if (geo === '$within') {
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 (geo === '$near' &&
typeof value.type === 'string' && Array.isArray(value.coordinates)) {
// geojson; cast the coordinates
value = value.coordinates;
} else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') &&
value.$geometry && typeof value.$geometry.type === 'string' &&
Array.isArray(value.$geometry.coordinates)) {
if (value.$maxDistance != null) {
value.$maxDistance = numbertype.castForQuery(value.$maxDistance);
}
if (value.$minDistance != null) {
value.$minDistance = numbertype.castForQuery(value.$minDistance);
}
if (utils.isMongooseObject(value.$geometry)) {
value.$geometry = value.$geometry.toObject({ virtuals: false });
}
value = value.$geometry.coordinates;
} else if (geo === '$geoWithin') {
if (!value.$geometry) {
throw new Error('$geoWithin must specify $geometry');
}
if (utils.isMongooseObject(value.$geometry)) {
value.$geometry = value.$geometry.toObject({ virtuals: false });
}
var geoWithinType = value.$geometry.type;
if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) {
throw new Error('Invalid geoJSON type for $geoWithin "' +
geoWithinType + '", must be "Polygon" or "MultiPolygon"');
}
value = value.$geometry.coordinates;
}
_cast(value, numbertype);
}
} else if (val === null || val === undefined) {
obj[path] = null;
continue;
} else if (val.constructor.name === 'Object') {
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),
$cond;
k = ks.length;
while (k--) {
$cond = ks[k];
nested = val[$cond];
if ($cond === '$exists') {
if (typeof nested !== 'boolean') {
throw new Error('$exists parameter must be Boolean');
}
continue;
}
if ($cond === '$type') {
if (typeof nested !== 'number' && typeof nested !== 'string') {
throw new Error('$type parameter must be number or string');
}
continue;
}
if ($cond === '$not') {
cast(schema, nested);
} else {
val[$cond] = schematype.castForQuery($cond, nested);
}
}
}
} else {
obj[path] = schematype.castForQuery(val);
}
}
}
return obj;
};
function _cast(val, numbertype) {
if (Array.isArray(val)) {
val.forEach(function(item, i) {
if (Array.isArray(item) || utils.isObject(item)) {
return _cast(item, numbertype);
}
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, numbertype);
val[nkey] = item;
} else {
val[nkey] = numbertype.castForQuery(item);
}
}
}
}

+ 45
- 27
node_modules/mongoose/lib/collection.js

@ -1,9 +1,9 @@
/*!
* Module dependencies.
*/
var STATES = require('./connectionstate')
var EventEmitter = require('events').EventEmitter;
var STATES = require('./connectionstate');
/**
* Abstract Collection constructor
@ -16,28 +16,34 @@ var STATES = require('./connectionstate')
* @api public
*/
function Collection (name, conn, opts) {
if (undefined === opts) opts = {};
if (undefined === opts.capped) opts.capped = {};
function Collection(name, conn, opts) {
if (opts === void 0) {
opts = {};
}
if (opts.capped === void 0) {
opts.capped = {};
}
opts.bufferCommands = undefined === opts.bufferCommands
? true
: opts.bufferCommands;
? true
: opts.bufferCommands;
if ('number' == typeof opts.capped) {
opts.capped = { size: opts.capped };
if (typeof opts.capped === 'number') {
opts.capped = {size: opts.capped};
}
this.opts = opts;
this.name = name;
this.collectionName = name;
this.conn = conn;
this.queue = [];
this.buffer = this.opts.bufferCommands;
this.emitter = new EventEmitter();
if (STATES.connected == this.conn.readyState) {
if (STATES.connected === this.conn.readyState) {
this.onOpen();
}
};
}
/**
* The collection name
@ -48,6 +54,15 @@ function Collection (name, conn, opts) {
Collection.prototype.name;
/**
* The collection name
*
* @api public
* @property collectionName
*/
Collection.prototype.collectionName;
/**
* The Connection instance
*
@ -63,10 +78,9 @@ Collection.prototype.conn;
* @api private
*/
Collection.prototype.onOpen = function () {
var self = this;
Collection.prototype.onOpen = function() {
this.buffer = false;
self.doQueue();
this.doQueue();
};
/**
@ -75,7 +89,7 @@ Collection.prototype.onOpen = function () {
* @api private
*/
Collection.prototype.onClose = function () {
Collection.prototype.onClose = function() {
if (this.opts.bufferCommands) {
this.buffer = true;
}
@ -90,7 +104,7 @@ Collection.prototype.onClose = function () {
* @api private
*/
Collection.prototype.addQueue = function (name, args) {
Collection.prototype.addQueue = function(name, args) {
this.queue.push([name, args]);
return this;
};
@ -101,11 +115,15 @@ Collection.prototype.addQueue = function (name, args) {
* @api private
*/
Collection.prototype.doQueue = function () {
for (var i = 0, l = this.queue.length; i < l; i++){
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 = [];
var _this = this;
process.nextTick(function() {
_this.emitter.emit('queue');
});
return this;
};
@ -113,7 +131,7 @@ Collection.prototype.doQueue = function () {
* Abstract method that drivers must implement.
*/
Collection.prototype.ensureIndex = function(){
Collection.prototype.ensureIndex = function() {
throw new Error('Collection#ensureIndex unimplemented by driver');
};
@ -121,7 +139,7 @@ Collection.prototype.ensureIndex = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.findAndModify = function(){
Collection.prototype.findAndModify = function() {
throw new Error('Collection#findAndModify unimplemented by driver');
};
@ -129,7 +147,7 @@ Collection.prototype.findAndModify = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.findOne = function(){
Collection.prototype.findOne = function() {
throw new Error('Collection#findOne unimplemented by driver');
};
@ -137,7 +155,7 @@ Collection.prototype.findOne = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.find = function(){
Collection.prototype.find = function() {
throw new Error('Collection#find unimplemented by driver');
};
@ -145,7 +163,7 @@ Collection.prototype.find = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.insert = function(){
Collection.prototype.insert = function() {
throw new Error('Collection#insert unimplemented by driver');
};
@ -153,7 +171,7 @@ Collection.prototype.insert = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.save = function(){
Collection.prototype.save = function() {
throw new Error('Collection#save unimplemented by driver');
};
@ -161,7 +179,7 @@ Collection.prototype.save = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.update = function(){
Collection.prototype.update = function() {
throw new Error('Collection#update unimplemented by driver');
};
@ -169,7 +187,7 @@ Collection.prototype.update = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.getIndexes = function(){
Collection.prototype.getIndexes = function() {
throw new Error('Collection#getIndexes unimplemented by driver');
};
@ -177,7 +195,7 @@ Collection.prototype.getIndexes = function(){
* Abstract method that drivers must implement.
*/
Collection.prototype.mapReduce = function(){
Collection.prototype.mapReduce = function() {
throw new Error('Collection#mapReduce unimplemented by driver');
};

+ 249
- 166
node_modules/mongoose/lib/connection.js

@ -2,17 +2,15 @@
* Module dependencies.
*/
var url = require('url')
, utils = require('./utils')
, EventEmitter = require('events').EventEmitter
, driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'
, Model = require('./model')
, Schema = require('./schema')
, Collection = require(driver + '/collection')
, STATES = require('./connectionstate')
, MongooseError = require('./error')
, assert =require('assert')
, muri = require('muri')
var utils = require('./utils');
var EventEmitter = require('events').EventEmitter;
var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native';
var Schema = require('./schema');
var Collection = require(driver + '/collection');
var STATES = require('./connectionstate');
var MongooseError = require('./error');
var muri = require('muri');
var PromiseProvider = require('./promise_provider');
/*!
* Protocol prefix regexp.
@ -22,6 +20,16 @@ var url = require('url')
var rgxProtocol = /^(?:.)+:\/\//;
/*!
* A list of authentication mechanisms that don't require a password for authentication.
* This is used by the authMechanismDoesNotRequirePassword method.
*
* @api private
*/
var authMechanismsWhichDontRequirePassword = [
'MONGODB-X509'
];
/**
* Connection constructor
*
@ -37,14 +45,16 @@ var rgxProtocol = /^(?:.)+:\/\//;
* @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.
* @event `fullsetup`: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
* @event `all`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
* @api public
*/
function Connection (base) {
function Connection(base) {
this.base = base;
this.collections = {};
this.models = {};
this.config = {autoIndex: true};
this.replica = false;
this.hosts = null;
this.host = null;
@ -53,10 +63,11 @@ function Connection (base) {
this.pass = null;
this.name = null;
this.options = null;
this.otherDbs = [];
this._readyState = STATES.disconnected;
this._closeCalled = false;
this._hasOpened = false;
};
}
/*!
* Inherit from EventEmitter
@ -84,21 +95,28 @@ Connection.prototype.__proto__ = EventEmitter.prototype;
*/
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;
get: function() {
return this._readyState;
},
set: function(val) {
if (!(val in STATES)) {
throw new Error('Invalid connection state: ' + val);
}
if (STATES.connected === val)
this._hasOpened = true;
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;
}
this.emit(STATES[val]);
if (STATES.connected === val) {
this._hasOpened = true;
}
this.emit(STATES[val]);
}
}
});
/**
@ -117,11 +135,20 @@ Connection.prototype.collections;
Connection.prototype.db;
/**
* A hash of the global options that are associated with this connection
*
* @property config
*/
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
@ -147,33 +174,37 @@ Connection.prototype.db;
* @api public
*/
Connection.prototype.open = function (host, database, port, options, callback) {
var self = this
, parsed
, uri;
Connection.prototype.open = function(host, database, port, options, callback) {
var parsed;
if ('string' === typeof database) {
if (typeof database === 'string') {
switch (arguments.length) {
case 2:
port = 27017;
break;
case 3:
switch (typeof port) {
case 'function':
callback = port, port = 27017;
callback = port;
port = 27017;
break;
case 'object':
options = port, port = 27017;
options = port;
port = 27017;
break;
}
break;
case 4:
if ('function' === typeof options)
callback = options, options = {};
if (typeof options === 'function') {
callback = options;
options = {};
}
}
} else {
switch (typeof database) {
case 'function':
callback = database, database = undefined;
callback = database;
database = undefined;
break;
case 'object':
options = database;
@ -219,32 +250,49 @@ Connection.prototype.open = function (host, database, port, options, callback) {
}
// authentication
if (options && options.user && options.pass) {
if (this.optionsProvideAuthenticationData(options)) {
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
// 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) {
this.config.autoIndex = options.config.autoIndex !== false;
}
this.name = database;
this.host = host;
this.port = port;
this._open(callback);
return this;
var _this = this;
var Promise = PromiseProvider.get();
var promise = new Promise.ES6(function(resolve, reject) {
_this._open(true, function(error) {
callback && callback(error);
if (error) {
reject(error);
if (!callback && !promise.$hasHandler) {
_this.emit('error', error);
}
return;
}
resolve();
});
});
return promise;
};
/**
@ -268,6 +316,8 @@ Connection.prototype.open = function (host, database, port, options, callback) {
* 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._
@ -289,13 +339,11 @@ Connection.prototype.open = function (host, database, port, options, callback) {
* @api public
*/
Connection.prototype.openSet = function (uris, database, options, callback) {
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) {
@ -309,7 +357,7 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
break;
}
if ('function' === typeof options) {
if (typeof options === 'function') {
callback = options;
options = {};
}
@ -320,10 +368,12 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
this.name = database;
break;
case 'function':
callback = database, database = null;
callback = database;
database = null;
break;
case 'object':
options = database, database = null;
options = database;
database = null;
break;
}
}
@ -350,20 +400,37 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
}
// authentication
if (options && options.user && options.pass) {
if (this.optionsProvideAuthenticationData(options)) {
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;
}
this._open(callback);
return this;
// global configuration options
if (options && options.config) {
this.config.autoIndex = options.config.autoIndex !== false;
}
var _this = this;
var Promise = PromiseProvider.get();
var promise = new Promise.ES6(function(resolve, reject) {
_this._open(true, function(error) {
callback && callback(error);
if (error) {
reject(error);
if (!callback && !promise.$hasHandler) {
_this.emit('error', error);
}
return;
}
resolve();
});
});
return promise;
};
/**
@ -377,10 +444,12 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
* @api private
*/
Connection.prototype.error = function (err, callback) {
if (callback) return callback(err);
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.
@ -389,31 +458,33 @@ Connection.prototype.error = function (err, callback) {
* @api private
*/
Connection.prototype._open = function (callback) {
Connection.prototype._open = function(emit, callback) {
this.readyState = STATES.connecting;
this._closeCalled = false;
var self = this;
var _this = this;
var method = this.replica
? 'doOpenSet'
: 'doOpen';
? 'doOpenSet'
: 'doOpen';
// open connection
this[method](function (err) {
this[method](function(err) {
if (err) {
self.readyState = STATES.disconnected;
if (self._hasOpened) {
if (callback) callback(err);
_this.readyState = STATES.disconnected;
if (_this._hasOpened) {
if (callback) {
callback(err);
}
} else {
self.error(err, callback);
_this.error(err, emit && callback);
}
return;
}
self.onOpen(callback);
_this.onOpen(callback);
});
}
};
/**
* Called when the connection is opened
@ -421,37 +492,38 @@ Connection.prototype._open = function (callback) {
* @api private
*/
Connection.prototype.onOpen = function (callback) {
var self = this;
Connection.prototype.onOpen = function(callback) {
var _this = this;
function open (err) {
function open(err, isAuth) {
if (err) {
self.readyState = STATES.disconnected;
if (self._hasOpened) {
if (callback) callback(err);
} else {
self.error(err, callback);
}
_this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
_this.error(err, callback);
return;
}
self.readyState = STATES.connected;
_this.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();
for (var i in _this.collections) {
if (utils.object.hasOwnProperty(_this.collections, i)) {
_this.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, open);
_this.emit('open');
}
else
// re-authenticate if we're not already connected #3871
if (this._readyState !== STATES.connected && this.shouldAuthenticate()) {
_this.db.authenticate(_this.user, _this.pass, _this.options.auth, function(err) {
open(err, true);
});
} else {
open();
}
};
/**
@ -462,36 +534,60 @@ Connection.prototype.onOpen = function (callback) {
* @api public
*/
Connection.prototype.close = function (callback) {
var self = this;
Connection.prototype.close = function(callback) {
var _this = this;
var Promise = PromiseProvider.get();
return new Promise.ES6(function(resolve, reject) {
_this._close(function(error) {
callback && callback(error);
if (error) {
reject(error);
return;
}
resolve();
});
});
};
/**
* Handles closing the connection
*
* @param {Function} callback
* @api private
*/
Connection.prototype._close = function(callback) {
var _this = this;
this._closeCalled = true;
switch (this.readyState){
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);
this.doClose(function(err) {
if (err) {
_this.error(err, callback);
} else {
self.onClose();
_this.onClose();
callback && callback();
}
});
break;
case 2: // connecting
this.once('open', function(){
self.close(callback);
this.once('open', function() {
_this.close(callback);
});
break;
case 3: // disconnecting
if (!callback) break;
this.once('close', function () {
if (!callback) {
break;
}
this.once('close', function() {
callback();
});
break;
@ -506,13 +602,16 @@ Connection.prototype.close = function (callback) {
* @api private
*/
Connection.prototype.onClose = function () {
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();
for (var i in this.collections) {
if (utils.object.hasOwnProperty(this.collections, i)) {
this.collections[i].onClose();
}
}
this.emit('close');
};
@ -528,9 +627,10 @@ Connection.prototype.onClose = function () {
* @api public
*/
Connection.prototype.collection = function (name, options) {
if (!(name in this.collections))
Connection.prototype.collection = function(name, options) {
if (!(name in this.collections)) {
this.collections[name] = new Collection(name, this, options);
}
return this.collections[name];
};
@ -566,31 +666,31 @@ Connection.prototype.collection = function (name, options) {
* @api public
*/
Connection.prototype.model = function (name, schema, collection) {
Connection.prototype.model = function(name, schema, collection) {
// collection name discovery
if ('string' == typeof schema) {
if (typeof schema === 'string') {
collection = schema;
schema = false;
}
if (utils.isObject(schema) && !(schema instanceof Schema)) {
if (utils.isObject(schema) && !schema.instanceOfSchema) {
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) {
if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
throw new MongooseError.OverwriteModelError(name);
}
return this.models[name];
}
var opts = { cache: false, connection: this }
var opts = {cache: false, connection: this};
var model;
if (schema instanceof Schema) {
if (schema && schema.instanceOfSchema) {
// compile a model
model = this.base.model(name, schema, collection, opts)
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.
@ -618,8 +718,8 @@ Connection.prototype.model = function (name, schema, collection) {
throw new MongooseError.MissingSchemaError(name);
}
if (this == model.prototype.db
&& (!collection || collection == model.collection.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
@ -630,9 +730,9 @@ Connection.prototype.model = function (name, schema, collection) {
return model;
}
return this.models[name] = model.__subclass(this, schema, collection);
}
this.models[name] = model.__subclass(this, schema, collection);
return this.models[name];
};
/**
* Returns an array of model names created on this connection.
@ -640,68 +740,51 @@ Connection.prototype.model = function (name, schema, collection) {
* @return {Array}
*/
Connection.prototype.modelNames = function () {
Connection.prototype.modelNames = function() {
return Object.keys(this.models);
}
};
/**
* Set profiling level.
*
* @param {Number|String} level either off (0), slow (1), or all (2)
* @param {Number} [ms] the threshold in milliseconds above which queries will be logged when in `slow` mode. defaults to 100.
* @param {Function} callback
* @api public
* @brief Returns if the connection requires authentication after it is opened. Generally if a
* username and password are both provided than authentication is needed, but in some cases a
* password is not required.
* @api private
* @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false.
*/
Connection.prototype.shouldAuthenticate = function() {
return (this.user !== null && this.user !== void 0) &&
((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword());
};
Connection.prototype.setProfiling = function (level, ms, callback) {
if (STATES.connected !== this.readyState) {
return this.on('open', this.setProfiling.bind(this, level, ms, callback));
}
if (!callback) callback = ms, ms = 100;
var cmd = {};
switch (level) {
case 0:
case 'off':
cmd.profile = 0;
break;
case 1:
case 'slow':
cmd.profile = 1;
if ('number' !== typeof ms) {
ms = parseInt(ms, 10);
if (isNaN(ms)) ms = 100;
}
cmd.slowms = ms;
break;
case 2:
case 'all':
cmd.profile = 2;
break;
default:
return callback(new Error('Invalid profiling level: '+ level));
/**
* @brief Returns a boolean value that specifies if the current authentication mechanism needs a
* password to authenticate according to the auth objects passed into the open/openSet methods.
* @api private
* @return {Boolean} true if the authentication mechanism specified in the options object requires
* a password, otherwise false.
*/
Connection.prototype.authMechanismDoesNotRequirePassword = function() {
if (this.options && this.options.auth) {
return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0;
}
this.db.executeDbCommand(cmd, function (err, resp) {
if (err) return callback(err);
var doc = resp.documents[0];
err = 1 === doc.ok
? null
: new Error('Could not set profiling level to: '+ level)
callback(err, doc);
});
return true;
};
/*!
* Noop.
/**
* @brief Returns a boolean value that specifies if the provided objects object provides enough
* data to authenticate with. Generally this is true if the username and password are both specified
* but in some authentication methods, a password is not required for authentication so only a username
* is required.
* @param {Object} [options] the options object passed into the open/openSet methods.
* @api private
* @return {Boolean} true if the provided options object provides enough data to authenticate with,
* otherwise false.
*/
function noop () {}
Connection.prototype.optionsProvideAuthenticationData = function(options) {
return (options) &&
(options.user) &&
((options.pass) || this.authMechanismDoesNotRequirePassword());
};
/*!
* Module exports.

+ 3
- 0
node_modules/mongoose/lib/connectionstate.js

@ -9,16 +9,19 @@ 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;

+ 1377
- 565
node_modules/mongoose/lib/document.js
File diff suppressed because it is too large
View File


+ 21
- 0
node_modules/mongoose/lib/document_provider.js

@ -0,0 +1,21 @@
'use strict';
/* eslint-env browser */
/*!
* 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;
}
return Document;
};

+ 5
- 0
node_modules/mongoose/lib/drivers/browser/ReadPreference.js

@ -0,0 +1,5 @@
/*!
* ignore
*/
module.exports = function() {};

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save