Updated mongoose

This commit is contained in:
Dobie Wollert
2015-11-24 22:08:58 -08:00
parent 71a05fb732
commit 8b5827c970
618 changed files with 122299 additions and 37754 deletions

3
node_modules/mongoose/.eslintignore generated vendored Normal file
View File

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

31
node_modules/mongoose/.eslintrc generated vendored Normal file
View File

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

3
node_modules/mongoose/.npmignore generated vendored
View File

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

9
node_modules/mongoose/.travis.yml generated vendored
View File

@ -1,7 +1,10 @@
language: node_js
sudo: false
node_js:
- 0.6
- 0.8
- 0.10
- "5"
- "4"
- "0.12"
- "0.10"
- "iojs"
services:
- mongodb

View File

@ -1,7 +1,5 @@
## 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.
### Reporting bugs
@ -41,7 +39,7 @@ If you have a question about Mongoose (not a bug report) please post it to eithe
- 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="..."
- any mocha flags can be specified with `T="..."`
### Documentation
@ -49,7 +47,7 @@ To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) ju
To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/LearnBoost/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here.
If you'd like to preview your documentation changes, first commit your changes to your local 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

1044
node_modules/mongoose/History.md generated vendored

File diff suppressed because it is too large Load Diff

147
node_modules/mongoose/README.md generated vendored
View File

@ -1,69 +1,83 @@
## What's Mongoose?
# Mongoose
Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
[![Build Status](https://api.travis-ci.org/Automattic/mongoose.png?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)
## 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)
- [10gen support](http://www.mongodb.org/display/DOCS/Technical+Support)
- [MongoDB support](http://www.mongodb.org/display/DOCS/Technical+Support)
- (irc) #mongoosejs on freenode
## Installation
First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads).
$ npm install mongoose
## Plugins
Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community.
Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin).
## Contributors
View all 90+ [contributors](https://github.com/learnboost/mongoose/graphs/contributors).
View all 100+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md) too!
## Get Involved
## Live Examples
<a href="http://runnable.com/mongoose" target="_blank"><img src="http://runnable.com/external/styles/assets/runnablebtn.png" style="width:67px;height:25px;"></a>
Stand up and be counted as a [contributor](https://github.com/LearnBoost/mongoose/blob/master/CONTRIBUTING.md) too!
## Installation
First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads). Then:
```sh
$ npm install mongoose
```
## Stability
The current stable branch is [master](https://github.com/Automattic/mongoose/tree/master). The [3.8.x](https://github.com/Automattic/mongoose/tree/3.8.x) branch contains legacy support for the 3.x release series, which will continue to be actively maintained until September 1, 2015.
## Overview
### Connecting to MongoDB
First, we need to define a connection. If your app uses only one database, you should use `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`.
```js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
```
Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._
**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
### Defining a Model
Models are defined through the `Schema` interface.
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
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,12 +94,13 @@ Aside from defining the structure of your documents and the types of data you're
The following example shows some of these features:
```js
var Comment = new Schema({
name : { type: String, default: 'hahaha' }
, age : { type: Number, min: 18, index: true }
, bio : { type: String, match: /[a-z]/ }
, date : { type: Date, default: Date.now }
, buff : Buffer
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
@ -98,6 +113,7 @@ The following example shows some of these features:
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,50 +121,73 @@ 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
```js
var myModel = mongoose.model('ModelName');
```
Or just do it all at once
```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
```js
var MyModel = mongoose.model('Ticket', mySchema);
```
Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection.
Once we have our model, we can then instantiate it, and save it:
```js
var instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
//
});
```
Or we can find documents from the same collection
```js
MyModel.find({}, function (err, docs) {
// docs.forEach
});
```
You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
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
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:
```js
// retrieve my model
var BlogPost = mongoose.model('BlogPost');
@ -161,9 +200,11 @@ Where `Comments` is a `Schema` we created. This means that creating embedded doc
post.save(function (err) {
if (!err) console.log('Success!');
});
```
The same goes for removing them:
```js
BlogPost.findById(myId, function (err, post) {
if (!err) {
post.comments[0].remove();
@ -172,6 +213,7 @@ The same goes for removing them:
});
}
});
```
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!
@ -187,6 +229,7 @@ You can intercept method arguments via middleware.
For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:
```js
schema.pre('set', function (next, path, val, typel) {
// `this` is the current Document
this.emit('set', path, val);
@ -194,13 +237,15 @@ For example, this would allow you to broadcast changes about your Documents ever
// Pass control to the next pre
next();
});
```
Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`:
```js
.pre(method, function firstPre (next, methodArg1, methodArg2) {
// Mutate methodArg1
next("altered-" + methodArg1.toString(), methodArg2);
})
});
// pre declaration is chainable
.pre(method, function secondPre (next, methodArg1, methodArg2) {
@ -215,27 +260,30 @@ Moreover, you can mutate the incoming `method` arguments so that subsequent midd
// and also equivalent to, with the example method arg
// values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
next();
})
});
```
#### Schema gotcha
`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation:
```js
new Schema({
broken: { type: Boolean }
, asset : {
name: String
, type: String // uh oh, it broke. asset will be interpreted as String
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
works: { type: Boolean },
asset : {
name: String,
type: { type: String } // works. asset is an object with a type property
}
});
```
### Driver access
@ -243,7 +291,8 @@ The driver being used defaults to [node-mongodb-native](https://github.com/mongo
## 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](http://github.com/visionmedia/dox)
and [acquit](http://github.com/vkarpov15/acquit).
## License

10
node_modules/mongoose/contRun.sh generated vendored Executable file
View File

@ -0,0 +1,10 @@
#!/bin/bash
make test
ret=$?
while [ $ret == 0 ]; do
make test
ret=$?
done

View File

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

101
node_modules/mongoose/examples/aggregate/aggregate.js generated vendored Normal file
View File

@ -0,0 +1,101 @@
// 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
node_modules/mongoose/examples/aggregate/package.json generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"name": "aggregate-example",
"private": "true",
"version": "0.0.0",
"description": "deps for aggregate example",
"main": "aggregate.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

17
node_modules/mongoose/examples/aggregate/person.js generated vendored Normal file
View File

@ -0,0 +1,17 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date,
gender: String,
likes: [String]
});
mongoose.model('Person', PersonSchema);
};

View File

@ -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,9 +9,16 @@ 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
@ -19,7 +26,7 @@ var CharacterSchema = Schema({
CharacterSchema.methods.attack = function() {
console.log('%s is attacking', this.name);
}
};
/**
* Character model
@ -43,7 +50,7 @@ mongoose.connect(uri, function (err) {
// we connected ok
example();
})
});
/**
* Use case
@ -55,7 +62,7 @@ function example () {
console.log('found', link);
link.attack(); // 'Link is attacking'
done();
})
});
}
/**
@ -66,5 +73,5 @@ function done (err) {
if (err) console.error(err);
mongoose.connection.db.dropDatabase(function() {
mongoose.disconnect();
})
});
}

1
node_modules/mongoose/examples/express/README.md generated vendored Normal file
View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,14 @@
{
"name": "connection-sharing",
"private": "true",
"version": "0.0.0",
"description": "ERROR: No README.md file found!",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "express": "3.1.1" },
"repository": "",
"author": "",
"license": "BSD"
}

View File

@ -0,0 +1,20 @@
var model = require('./modelA');
exports.home = function(req, res, next) {
model.find(function(err, docs) {
if (err) return next(err);
res.send(docs);
});
};
exports.modelName = function(req, res) {
res.send('my model name is ' + model.modelName);
};
exports.insert = function(req, res, next) {
model.create({ name: 'inserting ' + Date.now() }, function(err, doc) {
if (err) return next(err);
res.send(doc);
});
};

View File

@ -0,0 +1,22 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
// NOTE : This object must conform *precisely* to the geoJSON specification
// you cannot embed a geoJSON doc inside a model or anything like that- IT
// MUST BE VANILLA
var LocationObject = new Schema({
loc: {
type: { type: String },
coordinates: []
}
});
// define the index
LocationObject.index({ loc : '2dsphere' });
mongoose.model('Location', LocationObject);
};

View File

@ -0,0 +1,49 @@
// import async to make control flow simplier
var async = require('async');
// import the rest of the normal stuff
var mongoose = require('../../lib');
require('./geoJSONSchema.js')();
var Location = mongoose.model('Location');
// define some dummy data
// note: the type can be Point, LineString, or Polygon
var data = [
{ loc: { type: 'Point', coordinates: [-20.0, 5.0] }},
{ loc: { type: 'Point', coordinates: [6.0, 10.0] }},
{ loc: { type: 'Point', coordinates: [34.0, -50.0] }},
{ loc: { type: 'Point', coordinates: [-100.0, 70.0] }},
{ loc: { type: 'Point', coordinates: [38.0, 38.0] }}
];
mongoose.connect('mongodb://localhost/locations', function(err) {
if (err) throw err;
Location.on('index', function(err) {
if (err) throw err;
// create all of the dummy locations
async.each(data, function(item, cb) {
Location.create(item, cb);
}, function(err) {
if (err) throw err;
// create the location we want to search for
var coords = { type : 'Point', coordinates : [-5, 5] };
// search for it
Location.find({ loc : { $near : coords }}).limit(1).exec(function(err, res) {
if (err) throw err;
console.log("Closest to %s is %s", JSON.stringify(coords), res);
cleanup();
});
});
});
});
function cleanup() {
Location.remove(function() {
mongoose.disconnect();
});
}

View File

@ -0,0 +1,95 @@
// 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
node_modules/mongoose/examples/geospatial/package.json generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"name": "geospatial-example",
"private": "true",
"version": "0.0.0",
"description": "deps for geospatial example",
"main": "geospatial.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

28
node_modules/mongoose/examples/geospatial/person.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name : String,
age : Number,
birthday : Date,
gender: String,
likes: [String],
// define the geospatial field
loc: { type : [Number], index: '2d' }
});
// define a method to find the closest person
PersonSchema.methods.findClosest = function(cb) {
return this.model('Person').find({
loc : { $nearSphere : this.loc },
name : { $ne : this.name }
}).limit(1).exec(cb);
};
mongoose.model('Person', PersonSchema);
};

View File

@ -0,0 +1,40 @@
var mongoose = require('../../lib');
// import the global schema, this can be done in any file that needs the model
require('./person.js')();
// grab the person model object
var Person = mongoose.model("Person");
// connect to a server to do a quick write / read example
mongoose.connect('mongodb://localhost/persons', function(err) {
if (err) throw err;
Person.create({
name : 'bill',
age : 25,
birthday : new Date().setFullYear((new Date().getFullYear() - 25))
}, function(err, bill) {
if (err) throw err;
console.log("People added to db: %s", bill.toString());
Person.find({}, function(err, people) {
if (err) throw err;
people.forEach(function(person) {
console.log("People in the db: %s", person.toString());
});
// make sure to clean things up after we're done
setTimeout(function() { cleanup(); }, 2000);
});
});
});
function cleanup() {
Person.remove(function() {
mongoose.disconnect();
});
}

15
node_modules/mongoose/examples/globalschemas/person.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name : String,
age : Number,
birthday : Date
});
mongoose.model('Person', PersonSchema);
};

View File

@ -1,42 +0,0 @@
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/example-hooks');
var schema = Schema({ name: String });
schema.post('save', function () {
console.log('post save hook', arguments);
})
schema.pre('save', function (next) {
console.log('pre save');
next();
})
var M = mongoose.model('Hooks', schema);
var doc = new M({ name: 'hooooks' });
doc.save(function (err) {
console.log('save callback');
mongoose.disconnect();
})
////
Model.on('init', cb);
Model.on('remove', cb);
Model.on('update', cb);
// Model.update() and doc.save()
Model.on('insert', cb);
Model.on('save', cb);
var promise = Model.save(doc, options, callback);
//
var schema = new Schema(..);
schema.pre('save', function (next, done) {
})

84
node_modules/mongoose/examples/lean/lean.js generated vendored Normal file
View File

@ -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
node_modules/mongoose/examples/lean/package.json generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"name": "lean-example",
"private": "true",
"version": "0.0.0",
"description": "deps for lean example",
"main": "lean.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

17
node_modules/mongoose/examples/lean/person.js generated vendored Normal file
View File

@ -0,0 +1,17 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name : String,
age : Number,
birthday : Date,
gender: String,
likes: [String]
});
mongoose.model('Person', PersonSchema);
};

100
node_modules/mongoose/examples/mapreduce/mapreduce.js generated vendored Normal file
View File

@ -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
node_modules/mongoose/examples/mapreduce/package.json generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"name": "map-reduce-example",
"private": "true",
"version": "0.0.0",
"description": "deps for map reduce example",
"main": "mapreduce.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

16
node_modules/mongoose/examples/mapreduce/person.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name : String,
age : Number,
birthday : Date,
gender: String
});
mongoose.model('Person', PersonSchema);
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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);
/**
@ -71,7 +71,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 +79,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);
/**
@ -113,18 +113,18 @@ mongoose.connection.on('open', function() {
path: 'author.friends',
select: 'name',
options: { limit: 2 }
}
};
BlogPost.populate(docs, opts, function(err, docs) {
assert.ifError(err);
console.log('populated');
var s = require('util').inspect(docs, { depth: null })
var s = require('util').inspect(docs, { depth: null });
console.log(s);
done();
})
})
})
})
});
});
});
});
});
function done(err) {

View File

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

View File

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

View File

@ -0,0 +1,124 @@
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Console schema
*/
var consoleSchema = Schema({
name: String,
manufacturer: String,
released: Date
});
var Console = mongoose.model('Console', consoleSchema);
/**
* Game schema
*/
var gameSchema = Schema({
name: String,
developer: String,
released: Date,
consoles: [{
type: Schema.Types.ObjectId,
ref: 'Console'
}]
});
var Game = mongoose.model('Game', gameSchema);
/**
* Connect to the console database on localhost with
* the default port (27017)
*/
mongoose.connect('mongodb://localhost/console', function(err) {
// if we failed to connect, abort
if (err) throw err;
// we connected ok
createData();
});
/**
* Data generation
*/
function createData() {
Console.create(
{
name: 'Nintendo 64',
manufacturer: 'Nintendo',
released: 'September 29, 1996'
},
{
name: 'Super Nintendo',
manufacturer: 'Nintendo',
released: 'August 23, 1991'
},
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();
});
});
}

View File

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

View File

@ -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
node_modules/mongoose/examples/promises/package.json generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"name": "promise-example",
"private": "true",
"version": "0.0.0",
"description": "deps for promise example",
"main": "promise.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

15
node_modules/mongoose/examples/promises/person.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};

88
node_modules/mongoose/examples/promises/promise.js generated vendored Normal file
View File

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

View File

@ -0,0 +1,14 @@
{
"name": "query-builder-example",
"private": "true",
"version": "0.0.0",
"description": "deps for query builder example",
"main": "querybuilder.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

15
node_modules/mongoose/examples/querybuilder/person.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};

View File

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

View File

@ -0,0 +1,14 @@
{
"name": "replica-set-example",
"private": "true",
"version": "0.0.0",
"description": "deps for replica set example",
"main": "querybuilder.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": { "async": "*" },
"repository": "",
"author": "",
"license": "BSD"
}

15
node_modules/mongoose/examples/replicasets/person.js generated vendored Normal file
View File

@ -0,0 +1,15 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};

View File

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

View File

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

120
node_modules/mongoose/examples/schema/schema.js generated vendored Normal file
View File

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

View File

@ -0,0 +1,27 @@
// modules
var mongoose = require('../../../lib');
var Schema = mongoose.Schema;
// parse json
var raw = require('./schema.json');
// create a schema
var timeSignatureSchema = Schema(raw);
// compile the model
var TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema);
// create a TimeSignature document
var threeFour = new TimeSignature({
count: 3,
unit: 4,
description: "3/4",
additive: false,
created: new Date,
links: ["http://en.wikipedia.org/wiki/Time_signature"],
user_id: "518d31a0ef32bbfa853a9814"
});
// print its description
console.log(threeFour);

View File

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

21
node_modules/mongoose/examples/statics/person.js generated vendored Normal file
View File

@ -0,0 +1,21 @@
// import the necessary modules
var mongoose = require('../../lib');
var Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
var PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
// define a static
PersonSchema.statics.findPersonByName = function(name, cb) {
this.find({ name : new RegExp(name, 'i') }, cb);
};
mongoose.model('Person', PersonSchema);
};

41
node_modules/mongoose/examples/statics/statics.js generated vendored Normal file
View File

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

28
node_modules/mongoose/lib/ES6Promise.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
/* eslint no-unused-vars: 1 */
/**
* 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(fn) {
throw 'Can\'t use ES6 promise with mpromise style constructor';
}
ES6Promise.use = function(Promise) {
ES6Promise.ES6 = Promise;
};
module.exports = ES6Promise;

577
node_modules/mongoose/lib/aggregate.js generated vendored Normal file
View File

@ -0,0 +1,577 @@
/* eslint no-unused-vars: 1 */
/*!
* 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 (1 === arguments.length && util.isArray(arguments[0])) {
this.append.apply(this, arguments[0]);
} else {
this.append.apply(this, arguments);
}
}
/**
* Binds this aggregate to a model.
*
* @param {Model} model the model to which the aggregate is to be bound
* @return {Aggregate}
* @api 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 = 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 ('object' === typeof arg && !util.isArray(arg)) {
Object.keys(arg).forEach(function(field) {
fields[field] = arg[field];
});
} else if (1 === arguments.length && 'string' === typeof arg) {
arg.split(/\s+/).forEach(function(field) {
if (!field) return;
var include = '-' == field[0] ? 0 : 1;
if (include === 0) field = field.substring(1);
fields[field] = include;
});
} else {
throw new Error("Invalid project() argument. Must be string or object");
}
return this.append({ $project: fields });
};
/**
* Appends a new custom $group operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.group({ _id: "$department" });
*
* @see $group http://docs.mongodb.org/manual/reference/aggregation/group/
* @method group
* @memberOf Aggregate
* @param {Object} arg $group operator contents
* @return {Aggregate}
* @api public
*/
/**
* Appends a new custom $match operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.match({ department: { $in: [ "sales", "engineering" } } });
*
* @see $match http://docs.mongodb.org/manual/reference/aggregation/match/
* @method match
* @memberOf Aggregate
* @param {Object} arg $match operator contents
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $skip operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.skip(10);
*
* @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/
* @method skip
* @memberOf Aggregate
* @param {Number} num number of records to skip before next stage
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $limit operator to this aggregate pipeline.
*
* ####Examples:
*
* aggregate.limit(10);
*
* @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/
* @method limit
* @memberOf Aggregate
* @param {Number} num maximum number of records to pass to the next stage
* @return {Aggregate}
* @api public
*/
/**
* Appends a new $geoNear operator to this aggregate pipeline.
*
* ####NOTE:
*
* **MUST** be used as the first operator in the pipeline.
*
* ####Examples:
*
* aggregate.near({
* near: [40.724, -73.997],
* distanceField: "dist.calculated", // required
* maxDistance: 0.008,
* query: { type: "public" },
* includeLocs: "dist.location",
* uniqueDocs: true,
* num: 5
* });
*
* @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/
* @method near
* @memberOf Aggregate
* @param {Object} parameters
* @return {Aggregate}
* @api public
*/
Aggregate.prototype.near = function(arg) {
var op = {};
op.$geoNear = arg;
return this.append(op);
};
/*!
* define methods
*/
'group match skip limit out'.split(' ').forEach(function($operator) {
Aggregate.prototype[$operator] = function(arg) {
var op = {};
op['$' + $operator] = arg;
return this.append(op);
};
});
/**
* Appends new custom $unwind operator(s) to this aggregate pipeline.
*
* 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);
return this.append.apply(this, args.map(function(arg) {
return { $unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg };
}));
};
/**
* Appends a new $sort operator to this aggregate pipeline.
*
* If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
*
* If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
*
* ####Examples:
*
* // these are equivalent
* aggregate.sort({ field: 'asc', test: -1 });
* aggregate.sort('field -test');
*
* @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/
* @param {Object|String} arg
* @return {Aggregate} this
* @api public
*/
Aggregate.prototype.sort = function(arg) {
// TODO refactor to reuse the query builder logic
var sort = {};
if ('Object' === arg.constructor.name) {
var desc = ['desc', 'descending', -1];
Object.keys(arg).forEach(function(field) {
sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
});
} else if (1 === arguments.length && 'string' == typeof arg) {
arg.split(/\s+/).forEach(function(field) {
if (!field) return;
var ascend = '-' == field[0] ? -1 : 1;
if (ascend === -1) field = field.substring(1);
sort[field] = ascend;
});
} else {
throw new TypeError('Invalid sort() argument. Must be a string or object.');
}
return this.append({ $sort: sort });
};
/**
* Sets the readPreference option for the aggregation query.
*
* ####Example:
*
* Model.aggregate(..).read('primaryPreferred').exec(callback)
*
* @param {String} pref one of the listed preference options or their aliases
* @param {Array} [tags] optional tags for this query
* @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
* @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
*/
Aggregate.prototype.read = function(pref) {
if (!this.options) this.options = {};
read.apply(this, arguments);
return this;
};
/**
* 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;
};
/**
* 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();
if (this.options && this.options.cursor) {
if (this.options.cursor.async) {
return new Promise.ES6(function(resolve, reject) {
if (!_this._model.collection.buffer) {
process.nextTick(function() {
var cursor = _this._model.collection.
aggregate(_this._pipeline, _this.options || {});
resolve(cursor);
callback && callback(cursor);
});
return;
} else {
_this._model.collection.emitter.once('queue', function() {
var cursor = _this._model.collection.
aggregate(_this._pipeline, _this.options || {});
resolve(cursor);
callback && callback(null, cursor);
});
}
});
} else {
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);
});
});
};
/*!
* Helpers
*/
/**
* Checks whether an object is likely a pipeline operator
*
* @param {Object} obj object to check
* @return {Boolean}
* @api private
*/
function isOperator(obj) {
var k;
if ('object' !== typeof obj) {
return false;
}
k = Object.keys(obj);
return 1 === k.length && k.some(function(key) {
return '$' === key[0];
});
}
/*!
* Adds the appropriate `$match` pipeline step to the top of an aggregate's
* pipeline, should it's model is a non-root discriminator type. This is
* analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`.
*
* @param {Aggregate} aggregate Aggregate to prepare
*/
function prepareDiscriminatorPipeline(aggregate) {
var schema = aggregate._model.schema,
discriminatorMapping = schema && schema.discriminatorMapping;
if (discriminatorMapping && !discriminatorMapping.isRoot) {
var originalPipeline = aggregate._pipeline,
discriminatorKey = discriminatorMapping.key,
discriminatorValue = discriminatorMapping.value;
// If the first pipeline stage is a match and it doesn't specify a `__t`
// key, add the discriminator key to it. This allows for potential
// aggregation query optimizations not to be disturbed by this feature.
if (originalPipeline[0] && originalPipeline[0].$match &&
!originalPipeline[0].$match[discriminatorKey]) {
originalPipeline[0].$match[discriminatorKey] = discriminatorValue;
// `originalPipeline` is a ref, so there's no need for
// aggregate._pipeline = originalPipeline
} else 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;

97
node_modules/mongoose/lib/browser.js generated vendored Normal file
View File

@ -0,0 +1,97 @@
/**
* The [MongooseError](#error_MongooseError) constructor.
*
* @method Error
* @api public
*/
exports.Error = require('./error');
/**
* The Mongoose [Schema](#schema_Schema) constructor
*
* ####Example:
*
* var mongoose = require('mongoose');
* var Schema = mongoose.Schema;
* var CatSchema = new Schema(..);
*
* @method Schema
* @api public
*/
exports.Schema = require('./schema');
/**
* The various Mongoose Types.
*
* ####Example:
*
* var mongoose = require('mongoose');
* var array = mongoose.Types.Array;
*
* ####Types:
*
* - [ObjectId](#types-objectid-js)
* - [Buffer](#types-buffer-js)
* - [SubDocument](#types-embedded-js)
* - [Array](#types-array-js)
* - [DocumentArray](#types-documentarray-js)
*
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
*
* var ObjectId = mongoose.Types.ObjectId;
* var id1 = new ObjectId;
*
* @property Types
* @api public
*/
exports.Types = require('./types');
/**
* The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
*
* @method VirtualType
* @api public
*/
exports.VirtualType = require('./virtualtype');
/**
* The various Mongoose SchemaTypes.
*
* ####Note:
*
* _Alias of mongoose.Schema.Types for backwards compatibility._
*
* @property SchemaTypes
* @see Schema.SchemaTypes #schema_Schema.Types
* @api public
*/
exports.SchemaType = require('./schematype.js');
/**
* Internal utils
*
* @property utils
* @api private
*/
exports.utils = require('./utils.js');
/**
* The Mongoose browser [Document](#document-js) constructor.
*
* @method Document
* @api public
*/
exports.Document = require('./document_provider.js')();
/*!
* Module exports.
*/
if (typeof window !== 'undefined') {
window.mongoose = module.exports;
window.Buffer = Buffer;
}

105
node_modules/mongoose/lib/browserDocument.js generated vendored Normal file
View File

@ -0,0 +1,105 @@
/*!
* 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 instanceof Schema)) {
schema = new Schema(schema);
}
// When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
schema = this.schema || schema;
// Generate ObjectId if it is missing, but it requires a scheme
if ( !this.schema && schema.options._id ) {
obj = obj || {};
if ( obj._id === undefined ) {
obj._id = new ObjectId();
}
}
if ( !schema ) {
throw new MongooseError.MissingSchemaError();
}
this.$__setSchema(schema);
this.$__ = new InternalCache;
this.$__.emitter = new EventEmitter();
this.isNew = true;
this.errors = undefined;
//var schema = this.schema;
if ('boolean' === typeof fields) {
this.$__.strictMode = fields;
fields = undefined;
} else {
this.$__.strictMode = this.schema.options && this.schema.options.strict;
this.$__.selected = fields;
}
var required = this.schema.requiredPaths();
for (var i = 0; i < required.length; ++i) {
this.$__.activePaths.require(required[i]);
}
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;

211
node_modules/mongoose/lib/cast.js generated vendored Normal file
View File

@ -0,0 +1,211 @@
/*!
* Module dependencies.
*/
var utils = require('./utils');
var Types = require('./schema/index');
/**
* Handles internal casting for queries
*
* @param {Schema} schema
* @param {Object obj Object to cast
* @api private
*/
var cast = module.exports = function(schema, obj) {
var paths = Object.keys(obj),
i = paths.length,
any$conditionals,
schematype,
nested,
path,
type,
val;
while (i--) {
path = paths[i];
val = obj[path];
if ('$or' === path || '$nor' === path || '$and' === path) {
var k = val.length;
while (k--) {
val[k] = cast(schema, val[k]);
}
} else if (path === '$where') {
type = typeof val;
if ('string' !== type && 'function' !== type) {
throw new Error("Must have a string or function for $where");
}
if ('function' === type) {
obj[path] = val.toString();
}
continue;
} else if (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 = val.$near ? '$near' :
val.$nearSphere ? '$nearSphere' :
val.$within ? '$within' :
val.$geoIntersects ? '$geoIntersects' : '';
if (!geo) {
continue;
}
var numbertype = new Types.Number('__QueryCasting__');
var value = val[geo];
if (val.$maxDistance) {
val.$maxDistance = numbertype.castForQuery(val.$maxDistance);
}
if ('$within' == geo) {
var withinType = value.$center
|| value.$centerSphere
|| value.$box
|| value.$polygon;
if (!withinType) {
throw new Error('Bad $within paramater: ' + JSON.stringify(val));
}
value = withinType;
} else if ('$near' == geo &&
'string' == typeof value.type && Array.isArray(value.coordinates)) {
// geojson; cast the coordinates
value = value.coordinates;
} else if (('$near' == geo || '$nearSphere' == geo || '$geoIntersects' == geo) &&
value.$geometry && 'string' == typeof value.$geometry.type &&
Array.isArray(value.$geometry.coordinates)) {
// geojson; cast the coordinates
value = value.$geometry.coordinates;
}
(function _cast(val) {
if (Array.isArray(val)) {
val.forEach(function(item, i) {
if (Array.isArray(item) || utils.isObject(item)) {
return _cast(item);
}
val[i] = numbertype.castForQuery(item);
});
} else {
var nearKeys = Object.keys(val);
var nearLen = nearKeys.length;
while (nearLen--) {
var nkey = nearKeys[nearLen];
var item = val[nkey];
if (Array.isArray(item) || utils.isObject(item)) {
_cast(item);
val[nkey] = item;
} else {
val[nkey] = numbertype.castForQuery(item);
}
}
}
})(value);
}
} else if (val === null || val === undefined) {
obj[path] = null;
continue;
} else if ('Object' === val.constructor.name) {
any$conditionals = Object.keys(val).some(function(k) {
return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
});
if (!any$conditionals) {
obj[path] = schematype.castForQuery(val);
} else {
var ks = Object.keys(val),
$cond;
k = ks.length;
while (k--) {
$cond = ks[k];
nested = val[$cond];
if ('$exists' === $cond) {
if ('boolean' !== typeof nested) {
throw new Error("$exists parameter must be Boolean");
}
continue;
}
if ('$type' === $cond) {
if ('number' !== typeof nested) {
throw new Error("$type parameter must be Number");
}
continue;
}
if ('$not' === $cond) {
cast(schema, nested);
} else {
val[$cond] = schematype.castForQuery($cond, nested);
}
}
}
} else {
obj[path] = schematype.castForQuery(val);
}
}
}
return obj;
};

View File

@ -3,7 +3,8 @@
* Module dependencies.
*/
var STATES = require('./connectionstate')
var EventEmitter = require('events').EventEmitter;
var STATES = require('./connectionstate');
/**
* Abstract Collection constructor
@ -30,14 +31,16 @@ function Collection (name, conn, opts) {
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) {
this.onOpen();
}
};
}
/**
* The collection name
@ -48,6 +51,15 @@ function Collection (name, conn, opts) {
Collection.prototype.name;
/**
* The collection name
*
* @api public
* @property collectionName
*/
Collection.prototype.collectionName;
/**
* The Connection instance
*
@ -106,6 +118,10 @@ Collection.prototype.doQueue = function () {
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;
};

View File

@ -2,17 +2,14 @@
* 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'),
EventEmitter = require('events').EventEmitter,
driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native',
Schema = require('./schema'),
Collection = require(driver + '/collection'),
STATES = require('./connectionstate'),
MongooseError = require('./error'),
muri = require('muri');
/*!
* Protocol prefix regexp.
@ -22,6 +19,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
*
@ -45,6 +52,7 @@ 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 +61,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,14 +93,18 @@ Connection.prototype.__proto__ = EventEmitter.prototype;
*/
Object.defineProperty(Connection.prototype, 'readyState', {
get: function(){ return this._readyState; }
, set: function (val) {
get: function() { return this._readyState; },
set: function(val) {
if (!(val in STATES)) {
throw new Error('Invalid connection state: ' + val);
}
if (this._readyState !== val) {
this._readyState = val;
// loop over the otherDbs on this connection and change their state
for (var i = 0; i < this.otherDbs.length; i++) {
this.otherDbs[i].readyState = val;
}
if (STATES.connected === val)
this._hasOpened = true;
@ -117,11 +130,20 @@ Connection.prototype.collections;
Connection.prototype.db;
/**
* A hash of the global options that are associated with this connection
*
* @property global
*/
Connection.prototype.config;
/**
* Opens the connection to MongoDB.
*
* `options` is a hash with the following possible properties:
*
* config - passed to the connection config instance
* db - passed to the connection db instance
* server - passed to the connection server instance(s)
* replset - passed to the connection ReplSet instance
@ -148,14 +170,13 @@ Connection.prototype.db;
*/
Connection.prototype.open = function(host, database, port, options, callback) {
var self = this
, parsed
, uri;
var parsed;
if ('string' === typeof database) {
switch (arguments.length) {
case 2:
port = 27017;
break;
case 3:
switch (typeof port) {
case 'function':
@ -219,7 +240,7 @@ 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;
@ -239,6 +260,17 @@ Connection.prototype.open = function (host, database, port, options, callback) {
this.user = this.pass = undefined;
}
// global configuration options
if (options && options.config) {
if (options.config.autoIndex === false) {
this.config.autoIndex = false;
}
else {
this.config.autoIndex = true;
}
}
this.name = database;
this.host = host;
this.port = port;
@ -266,15 +298,22 @@ Connection.prototype.open = function (host, database, port, options, callback) {
* user - username for authentication
* pass - password for authentication
* auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
* mongos - Boolean - if true, enables High Availability support for mongos
*
* _Options passed take precedence over options included in connection strings._
*
* ####Notes:
*
* _If connecting to multiple mongos servers, set the `mongos` option to true._
*
* conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
*
* Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.
* Mongoose defaults the server `auto_reconnect` options to true which can be overridden.
* See the node-mongodb-native driver instance for options that it understands.
*
* _Options passed take precedence over options included in connection strings._
*
* @param {String} uris comma-separated mongodb:// `URI`s
* @param {String} [database] database name if not included in `uris`
* @param {Object} [options] passed to the internal driver
@ -289,8 +328,6 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
uris = 'mongodb://' + uris;
}
var self = this;
switch (arguments.length) {
case 3:
switch (typeof database) {
@ -345,7 +382,7 @@ 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;
@ -357,6 +394,17 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
this.user = this.pass = undefined;
}
// global configuration options
if (options && options.config) {
if (options.config.autoIndex === false) {
this.config.autoIndex = false;
}
else {
this.config.autoIndex = true;
}
}
this._open(callback);
return this;
};
@ -375,7 +423,7 @@ Connection.prototype.openSet = function (uris, database, options, callback) {
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.
@ -408,7 +456,7 @@ Connection.prototype._open = function (callback) {
self.onOpen(callback);
});
}
};
/**
* Called when the connection is opened
@ -419,9 +467,9 @@ Connection.prototype._open = function (callback) {
Connection.prototype.onOpen = function(callback) {
var self = this;
function open (err) {
function open(err, isAuth) {
if (err) {
self.readyState = STATES.disconnected;
self.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
if (self._hasOpened) {
if (callback) callback(err);
} else {
@ -439,14 +487,16 @@ Connection.prototype.onOpen = function (callback) {
callback && callback();
self.emit('open');
};
}
// re-authenticate
if (self.user && self.pass) {
self.db.authenticate(self.user, self.pass, self.options.auth, open);
}
else
if (this.shouldAuthenticate()) {
self.db.authenticate(self.user, self.pass, self.options.auth, function(err) {
open(err, true);
});
} else {
open();
}
};
/**
@ -467,6 +517,7 @@ Connection.prototype.close = function (callback) {
break;
case 1: // connected
case 4: // unauthorized
this.readyState = STATES.disconnecting;
this.doClose(function(err) {
if (err) {
@ -580,12 +631,12 @@ Connection.prototype.model = function (name, schema, collection) {
return this.models[name];
}
var opts = { cache: false, connection: this }
var opts = { cache: false, connection: this };
var model;
if (schema instanceof Schema) {
// 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.
@ -627,7 +678,7 @@ Connection.prototype.model = function (name, schema, collection) {
}
return this.models[name] = model.__subclass(this, schema, collection);
}
};
/**
* Returns an array of model names created on this connection.
@ -637,66 +688,49 @@ Connection.prototype.model = function (name, schema, collection) {
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
*/
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));
}
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);
});
};
/*!
* Noop.
/**
* @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.pass != null) || this.authMechanismDoesNotRequirePassword());
};
function noop () {}
/**
* @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;
}
return true;
};
/**
* @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.
*/
Connection.prototype.optionsProvideAuthenticationData = function(options) {
return (options) &&
(options.user) &&
((options.pass) || this.authMechanismDoesNotRequirePassword());
};
/*!
* Module exports.

View File

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

1408
node_modules/mongoose/lib/document.js generated vendored

File diff suppressed because it is too large Load Diff

20
node_modules/mongoose/lib/document_provider.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
'use strict';
/*!
* Module dependencies.
*/
var Document = require('./document.js');
var BrowserDocument = require('./browserDocument.js');
/**
* Returns the Document constructor for the current context
*
* @api private
*/
module.exports = function() {
if (typeof window !== 'undefined' && typeof document !== 'undefined' && document === window.document) {
return BrowserDocument;
} else {
return Document;
}
};

View File

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

12
node_modules/mongoose/lib/drivers/browser/binary.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
/*!
* Module dependencies.
*/
var Binary = require('bson').Binary;
/*!
* Module exports.
*/
module.exports = exports = Binary;

7
node_modules/mongoose/lib/drivers/browser/index.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
/*!
* Module exports.
*/
exports.Binary = require('./binary');
exports.ObjectId = require('./objectid');
exports.ReadPreference = require('./ReadPreference');

14
node_modules/mongoose/lib/drivers/browser/objectid.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
/*!
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
* @constructor NodeMongoDbObjectId
* @see ObjectId
*/
var ObjectId = require('bson').ObjectID;
/*!
* ignore
*/
module.exports = exports = ObjectId;

17
node_modules/mongoose/lib/drivers/index.js generated vendored Normal file
View File

@ -0,0 +1,17 @@
/*!
* ignore
*/
var driver;
if (typeof window === 'undefined') {
driver = require(global.MONGOOSE_DRIVER_PATH || './node-mongodb-native');
} else {
driver = require('./browser');
}
/*!
* ignore
*/
module.exports = driver;

View File

@ -0,0 +1,45 @@
/*!
* Module dependencies.
*/
var mongodb = require('mongodb');
var ReadPref = mongodb.ReadPreference;
/*!
* Converts arguments to ReadPrefs the driver
* can understand.
*
* @param {String|Array} pref
* @param {Array} [tags]
*/
module.exports = function readPref(pref, tags) {
if (Array.isArray(pref)) {
tags = pref[1];
pref = pref[0];
}
if (pref instanceof ReadPref) {
return pref;
}
switch (pref) {
case 'p':
pref = 'primary';
break;
case 'pp':
pref = 'primaryPreferred';
break;
case 's':
pref = 'secondary';
break;
case 'sp':
pref = 'secondaryPreferred';
break;
case 'n':
pref = 'nearest';
break;
}
return new ReadPref(pref, tags);
};

View File

@ -3,6 +3,6 @@
* Module dependencies.
*/
var Binary = require('mongodb').BSONPure.Binary;
var Binary = require('mongodb').Binary;
module.exports = exports = Binary;

View File

@ -3,10 +3,9 @@
* Module dependencies.
*/
var MongooseCollection = require('../../collection')
, Collection = require('mongodb').Collection
, STATES = require('../../connectionstate')
, utils = require('../../utils')
var MongooseCollection = require('../../collection'),
Collection = require('mongodb').Collection,
utils = require('../../utils');
/**
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation.
@ -50,17 +49,21 @@ NativeCollection.prototype.onOpen = function () {
if (err) return callback(err);
// discover if this collection exists and if it is capped
c.options(function (err, exists) {
if (err) return callback(err);
self.conn.db.listCollections({ name: self.name }).toArray(function(err, docs) {
if (err) {
return callback(err);
}
var doc = docs[0];
var exists = !!doc;
if (exists) {
if (exists.capped) {
if (doc.options && doc.options.capped) {
callback(null, c);
} else {
var msg = 'A non-capped collection exists with the name: ' + self.name + '\n\n'
+ ' To use this collection as a capped collection, please '
+ 'first convert it.\n'
+ ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'
+ ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped';
err = new Error(msg);
callback(err);
}
@ -81,7 +84,7 @@ NativeCollection.prototype.onOpen = function () {
self.collection = collection;
MongooseCollection.prototype.onOpen.call(self);
}
};
}
};
/**
@ -99,6 +102,16 @@ NativeCollection.prototype.onClose = function () {
*/
for (var i in Collection.prototype) {
// Janky hack to work around gh-3005 until we can get rid of the mongoose
// collection abstraction
try {
if (typeof Collection.prototype[i] !== 'function') {
continue;
}
} catch (e) {
continue;
}
(function(i) {
NativeCollection.prototype[i] = function() {
if (this.buffer) {
@ -106,61 +119,75 @@ for (var i in Collection.prototype) {
return;
}
var collection = this.collection
, args = arguments
, self = this
, debug = self.conn.base.options.debug;
var collection = this.collection,
args = arguments,
self = this,
debug = self.conn.base.options.debug;
if (debug) {
if ('function' === typeof debug) {
debug.apply(debug
, [self.name, i].concat(utils.args(args, 0, args.length - 1)));
} else {
console.error('\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s'
, self.name
, i
, print(args[0])
, print(args[1])
, print(args[2])
, print(args[3]))
this.$print(self.name, i, args);
}
}
collection[i].apply(collection, args);
return collection[i].apply(collection, args);
};
})(i);
}
/*!
/**
* Debug print helper
*
* @api public
*/
function print (arg) {
NativeCollection.prototype.$print = function(name, i, args) {
console.error(
'\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s',
name,
i,
this.$format(args[0]),
this.$format(args[1]),
this.$format(args[2]),
this.$format(args[3]));
};
/**
* Formatter for debug print args
*
* @api public
*/
NativeCollection.prototype.$format = function(arg) {
var type = typeof arg;
if ('function' === type || 'undefined' === type) return '';
return format(arg);
}
};
/*!
* Debug print helper
*/
function format(obj, sub) {
var x = utils.clone(obj);
var x = utils.clone(obj, { retainKeyOrder: 1 });
var representation;
if (x) {
if ('Binary' === x.constructor.name) {
x = '[object Buffer]';
} else if ('ObjectID' === x.constructor.name) {
var representation = 'ObjectId("' + x.toHexString() + '")';
representation = 'ObjectId("' + x.toHexString() + '")';
x = { inspect: function() { return representation; } };
} else if ('Date' === x.constructor.name) {
var representation = 'new Date("' + x.toUTCString() + '")';
representation = 'new Date("' + x.toUTCString() + '")';
x = { inspect: function() { return representation; } };
} else if ('Object' === x.constructor.name) {
var keys = Object.keys(x)
, i = keys.length
, key
while (i--) {
var keys = Object.keys(x);
var numKeys = keys.length;
var key;
for (var i = 0; i < numKeys; ++i) {
key = keys[i];
if (x[key]) {
if ('Binary' === x[key].constructor.name) {
@ -168,18 +195,18 @@ function format (obj, sub) {
} else if ('Object' === x[key].constructor.name) {
x[key] = format(x[key], true);
} else if ('ObjectID' === x[key].constructor.name) {
;(function(x){
(function(x) {
var representation = 'ObjectId("' + x[key].toHexString() + '")';
x[key] = { inspect: function() { return representation; } };
})(x)
})(x);
} else if ('Date' === x[key].constructor.name) {
;(function(x){
(function(x) {
var representation = 'new Date("' + x[key].toUTCString() + '")';
x[key] = { inspect: function() { return representation; } };
})(x)
})(x);
} else if (Array.isArray(x[key])) {
x[key] = x[key].map(function(o) {
return format(o, true)
return format(o, true);
});
}
}
@ -191,7 +218,7 @@ function format (obj, sub) {
return require('util')
.inspect(x, false, 10, true)
.replace(/\n/g, '')
.replace(/\s{2,}/g, ' ')
.replace(/\s{2,}/g, ' ');
}
/**

View File

@ -2,13 +2,13 @@
* Module dependencies.
*/
var MongooseConnection = require('../../connection')
, mongo = require('mongodb')
, Db = mongo.Db
, Server = mongo.Server
, Mongos = mongo.Mongos
, STATES = require('../../connectionstate')
, ReplSetServers = mongo.ReplSetServers;
var MongooseConnection = require('../../connection'),
mongo = require('mongodb'),
Db = mongo.Db,
Server = mongo.Server,
Mongos = mongo.Mongos,
STATES = require('../../connectionstate'),
ReplSetServers = mongo.ReplSet;
/**
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
@ -20,7 +20,14 @@ var MongooseConnection = require('../../connection')
function NativeConnection() {
MongooseConnection.apply(this, arguments);
this._listening = false;
};
}
/**
* Expose the possible connection states.
* @api public
*/
NativeConnection.STATES = STATES;
/*!
* Inherits from Connection.
@ -37,12 +44,14 @@ NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
*/
NativeConnection.prototype.doOpen = function(fn) {
if (this.db) {
mute(this);
}
var server = new Server(this.host, this.port, this.options.server);
if (this.options && this.options.mongos) {
var mongos = new Mongos([server], this.options.mongos);
this.db = new Db(this.name, mongos, this.options.db);
} else {
this.db = new Db(this.name, server, this.options.db);
}
var self = this;
this.db.open(function(err) {
@ -54,6 +63,66 @@ NativeConnection.prototype.doOpen = function (fn) {
return this;
};
/**
* Switches to a different database using the same connection pool.
*
* Returns a new connection object, with the new db.
*
* @param {String} name The database name
* @return {Connection} New Connection Object
* @api public
*/
NativeConnection.prototype.useDb = function(name) {
// we have to manually copy all of the attributes...
var newConn = new this.constructor();
newConn.name = name;
newConn.base = this.base;
newConn.collections = {};
newConn.models = {};
newConn.replica = this.replica;
newConn.hosts = this.hosts;
newConn.host = this.host;
newConn.port = this.port;
newConn.user = this.user;
newConn.pass = this.pass;
newConn.options = this.options;
newConn._readyState = this._readyState;
newConn._closeCalled = this._closeCalled;
newConn._hasOpened = this._hasOpened;
newConn._listening = false;
// First, when we create another db object, we are not guaranteed to have a
// db object to work with. So, in the case where we have a db object and it
// is connected, we can just proceed with setting everything up. However, if
// we do not have a db or the state is not connected, then we need to wait on
// the 'open' event of the connection before doing the rest of the setup
// the 'connected' event is the first time we'll have access to the db object
var self = this;
if (this.db && this._readyState === STATES.connected) {
wireup();
} else {
this.once('connected', wireup);
}
function wireup() {
newConn.db = self.db.db(name);
newConn.onOpen();
// setup the events appropriately
listen(newConn);
}
newConn.name = name;
// push onto the otherDbs stack, this is used when state changes
this.otherDbs.push(newConn);
newConn.otherDbs.push(this);
return newConn;
};
/*!
* Register listeners for important events and bubble appropriately.
*/
@ -78,6 +147,10 @@ function listen (conn) {
conn.db.on('error', function(err) {
conn.emit('error', err);
});
conn.db.on('reconnect', function() {
conn.readyState = STATES.connected;
conn.emit('reconnected');
});
conn.db.on('timeout', function(err) {
var error = new Error(err && err.err || 'connection timeout');
conn.emit('error', error);
@ -85,23 +158,12 @@ function listen (conn) {
conn.db.on('open', function(err, db) {
if (STATES.disconnected === conn.readyState && db && db.databaseName) {
conn.readyState = STATES.connected;
conn.emit('reconnected')
conn.emit('reconnected');
}
})
}
/*!
* Remove listeners registered in `listen`
*/
function mute (conn) {
if (!conn.db) throw new Error('missing db');
conn.db.removeAllListeners("close");
conn.db.removeAllListeners("error");
conn.db.removeAllListeners("timeout");
conn.db.removeAllListeners("open");
conn.db.removeAllListeners("fullsetup");
conn._listening = false;
});
conn.db.on('parseError', function(err) {
conn.emit('parseError', err);
});
}
/**
@ -115,18 +177,14 @@ function mute (conn) {
*/
NativeConnection.prototype.doOpenSet = function(fn) {
if (this.db) {
mute(this);
}
var servers = []
, self = this;
var servers = [],
self = this;
this.hosts.forEach(function(server) {
var host = server.host || server.ipc;
var port = server.port || 27017;
servers.push(new Server(host, port, self.options.server));
})
});
var server = this.options.mongos
? new Mongos(servers, this.options.mongos)
@ -134,7 +192,7 @@ NativeConnection.prototype.doOpenSet = function (fn) {
this.db = new Db(this.name, server, this.options.db);
this.db.on('fullsetup', function() {
self.emit('fullsetup')
self.emit('fullsetup');
});
this.db.open(function(err) {
@ -158,7 +216,7 @@ NativeConnection.prototype.doClose = function (fn) {
this.db.close();
if (fn) fn();
return this;
}
};
/**
* Prepares default connection options for the node-mongodb-native driver.
@ -182,9 +240,10 @@ NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
var opts = connStrOpts || {};
Object.keys(opts).forEach(function(name) {
switch (name) {
case 'ssl':
case 'poolSize':
if ('undefined' == typeof o.server.poolSize) {
o.server.poolSize = o.replset.poolSize = opts[name];
if ('undefined' == typeof o.server[name]) {
o.server[name] = o.replset[name] = opts[name];
}
break;
case 'slaveOk':
@ -197,7 +256,6 @@ NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
o.server.auto_reconnect = opts[name];
}
break;
case 'ssl':
case 'socketTimeoutMS':
case 'connectTimeoutMS':
if ('undefined' == typeof o.server.socketOptions[name]) {
@ -256,7 +314,7 @@ NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
}
break;
}
})
});
if (!('auto_reconnect' in o.server)) {
o.server.auto_reconnect = true;
@ -278,7 +336,7 @@ NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
validate(o);
return o;
}
};
/*!
* Validates the driver db options.

View File

@ -0,0 +1,7 @@
/*!
* Module exports.
*/
exports.Binary = require('./binary');
exports.ObjectId = require('./objectid');
exports.ReadPreference = require('./ReadPreference');

View File

@ -5,25 +5,10 @@
* @see ObjectId
*/
var ObjectId = require('mongodb').BSONPure.ObjectID;
var ObjectId = require('mongodb').ObjectId;
/*!
* ignore
*/
var ObjectIdToString = ObjectId.toString.bind(ObjectId);
module.exports = exports = ObjectId;
ObjectId.fromString = function(str){
// patch native driver bug in V0.9.6.4
if (!('string' === typeof str && 24 === str.length)) {
throw new Error("Invalid ObjectId");
}
return ObjectId.createFromHexString(str);
};
ObjectId.toString = function(oid){
if (!arguments.length) return ObjectIdToString();
return oid.toHexString();
};

38
node_modules/mongoose/lib/error.js generated vendored
View File

@ -8,16 +8,21 @@
function MongooseError(msg) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack
}
this.message = msg;
this.name = 'MongooseError';
};
}
/*!
* Inherits from Error.
*/
MongooseError.prototype.__proto__ = Error.prototype;
MongooseError.prototype = Object.create(Error.prototype);
MongooseError.prototype.constructor = Error;
/*!
* Module exports.
@ -25,15 +30,26 @@ MongooseError.prototype.__proto__ = Error.prototype;
module.exports = exports = MongooseError;
/**
* The default built-in validator error messages.
*
* @see Error.messages #error_messages_MongooseError-messages
* @api public
*/
MongooseError.messages = require('./error/messages');
// backward compat
MongooseError.Messages = MongooseError.messages;
/*!
* Expose subclasses
*/
MongooseError.CastError = require('./errors/cast');
MongooseError.DocumentError = require('./errors/document');
MongooseError.ValidationError = require('./errors/validation')
MongooseError.ValidatorError = require('./errors/validator')
MongooseError.VersionError =require('./errors/version')
MongooseError.OverwriteModelError = require('./errors/overwriteModel')
MongooseError.MissingSchemaError = require('./errors/missingSchema')
MongooseError.DivergentArrayError = require('./errors/divergentArray')
MongooseError.CastError = require('./error/cast');
MongooseError.ValidationError = require('./error/validation');
MongooseError.ValidatorError = require('./error/validator');
MongooseError.VersionError = require('./error/version');
MongooseError.OverwriteModelError = require('./error/overwriteModel');
MongooseError.MissingSchemaError = require('./error/missingSchema');
MongooseError.DivergentArrayError = require('./error/divergentArray');

View File

@ -0,0 +1,33 @@
/* eslint no-unused-vars: 1 */
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
/*!
* MissingSchema Error constructor.
*
* @inherits MongooseError
*/
function MissingSchemaError(name) {
var msg = 'Schema hasn\'t been registered for document.\n'
+ 'Use mongoose.Document(name, schema)';
MongooseError.call(this, msg);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'MissingSchemaError';
}
/*!
* Inherits from MongooseError.
*/
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = MissingSchemaError;

View File

@ -2,7 +2,7 @@
* Module dependencies.
*/
var MongooseError = require('../error');
var MongooseError = require('../error.js');
/**
* Casting Error constructor.
@ -13,20 +13,27 @@ var MongooseError = require('../error');
* @api private
*/
function CastError (type, value, path) {
function CastError(type, value, path, reason) {
MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"');
Error.captureStackTrace(this, arguments.callee);
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack
}
this.name = 'CastError';
this.type = type;
this.kind = type;
this.value = value;
this.path = path;
};
this.reason = reason;
}
/*!
* Inherits from MongooseError.
*/
CastError.prototype.__proto__ = MongooseError.prototype;
CastError.prototype = Object.create(MongooseError.prototype);
CastError.prototype.constructor = MongooseError;
/*!
* exports

View File

@ -3,7 +3,7 @@
* Module dependencies.
*/
var MongooseError = require('../error');
var MongooseError = require('../error.js');
/*!
* DivergentArrayError constructor.
@ -19,19 +19,21 @@ function DivergentArrayError (paths) {
+ 'the entire array is not supported. The following '
+ 'path(s) would have been modified unsafely:\n'
+ ' ' + paths.join('\n ') + '\n'
+ 'Use Model.update() to update these arrays instead.'
+ 'Use Model.update() to update these arrays instead.';
// TODO write up a docs page (FAQ) and link to it
MongooseError.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'DivergentArrayError';
};
}
/*!
* Inherits from MongooseError.
*/
DivergentArrayError.prototype.__proto__ = MongooseError.prototype;
DivergentArrayError.prototype = Object.create(MongooseError.prototype);
DivergentArrayError.prototype.constructor = MongooseError;
/*!
* exports

43
node_modules/mongoose/lib/error/messages.js generated vendored Normal file
View File

@ -0,0 +1,43 @@
/**
* The default built-in validator error messages. These may be customized.
*
* // customize within each schema or globally like so
* var mongoose = require('mongoose');
* mongoose.Error.messages.String.enum = "Your custom message for {PATH}.";
*
* As you might have noticed, error messages support basic templating
*
* - `{PATH}` is replaced with the invalid document path
* - `{VALUE}` is replaced with the invalid value
* - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined"
* - `{MIN}` is replaced with the declared min value for the Number.min validator
* - `{MAX}` is replaced with the declared max value for the Number.max validator
*
* Click the "show code" link below to see all defaults.
*
* @property messages
* @receiver MongooseError
* @api public
*/
var msg = module.exports = exports = {};
msg.general = {};
msg.general.default = "Validator failed for path `{PATH}` with value `{VALUE}`";
msg.general.required = "Path `{PATH}` is required.";
msg.Number = {};
msg.Number.min = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).";
msg.Number.max = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).";
msg.Date = {};
msg.Date.min = "Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).";
msg.Date.max = "Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).";
msg.String = {};
msg.String.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`.";
msg.String.match = "Path `{PATH}` is invalid ({VALUE}).";
msg.String.minlength = "Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).";
msg.String.maxlength = "Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).";

View File

@ -3,7 +3,7 @@
* Module dependencies.
*/
var MongooseError = require('../error');
var MongooseError = require('../error.js');
/*!
* MissingSchema Error constructor.
@ -15,15 +15,16 @@ function MissingSchemaError (name) {
var msg = 'Schema hasn\'t been registered for model "' + name + '".\n'
+ 'Use mongoose.model(name, schema)';
MongooseError.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'MissingSchemaError';
};
}
/*!
* Inherits from MongooseError.
*/
MissingSchemaError.prototype.__proto__ = MongooseError.prototype;
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;
/*!
* exports

View File

@ -3,7 +3,7 @@
* Module dependencies.
*/
var MongooseError = require('../error');
var MongooseError = require('../error.js');
/*!
* OverwriteModel Error constructor.
@ -13,15 +13,16 @@ var MongooseError = require('../error');
function OverwriteModelError(name) {
MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.');
Error.captureStackTrace(this, arguments.callee);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'OverwriteModelError';
};
}
/*!
* Inherits from MongooseError.
*/
OverwriteModelError.prototype.__proto__ = MongooseError.prototype;
OverwriteModelError.prototype = Object.create(MongooseError.prototype);
OverwriteModelError.prototype.constructor = MongooseError;
/*!
* exports

62
node_modules/mongoose/lib/error/validation.js generated vendored Normal file
View File

@ -0,0 +1,62 @@
/*!
* Module requirements
*/
var MongooseError = require('../error.js');
/**
* Document Validation Error
*
* @api private
* @param {Document} instance
* @inherits MongooseError
*/
function ValidationError(instance) {
if (instance && instance.constructor.name === 'model') {
MongooseError.call(this, instance.constructor.modelName + " validation failed");
} else {
MongooseError.call(this, "Validation failed");
}
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack
}
this.name = 'ValidationError';
this.errors = {};
if (instance) {
instance.errors = this.errors;
}
}
/*!
* Inherits from MongooseError.
*/
ValidationError.prototype = Object.create(MongooseError.prototype);
ValidationError.prototype.constructor = MongooseError;
/**
* Console.log helper
*/
ValidationError.prototype.toString = function() {
var ret = this.name + ': ';
var msgs = [];
Object.keys(this.errors).forEach(function(key) {
if (this == this.errors[key]) return;
msgs.push(String(this.errors[key]));
}, this);
return ret + msgs.join(', ');
};
/*!
* Module exports
*/
module.exports = exports = ValidationError;

71
node_modules/mongoose/lib/error/validator.js generated vendored Normal file
View File

@ -0,0 +1,71 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error.js');
var errorMessages = MongooseError.messages;
/**
* Schema validator error
*
* @param {Object} properties
* @inherits MongooseError
* @api private
*/
function ValidatorError(properties) {
var msg = properties.message;
if (!msg) {
msg = errorMessages.general.default;
}
this.properties = properties;
var message = this.formatMessage(msg, properties);
MongooseError.call(this, message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack
}
this.name = 'ValidatorError';
this.kind = properties.type;
this.path = properties.path;
this.value = properties.value;
}
/*!
* Inherits from MongooseError
*/
ValidatorError.prototype = Object.create(MongooseError.prototype);
ValidatorError.prototype.constructor = MongooseError;
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function(msg, properties) {
var propertyNames = Object.keys(properties);
for (var i = 0; i < propertyNames.length; ++i) {
var propertyName = propertyNames[i];
if (propertyName === 'message') {
continue;
}
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
}
return msg;
};
/*!
* toString helper
*/
ValidatorError.prototype.toString = function() {
return this.message;
};
/*!
* exports
*/
module.exports = ValidatorError;

View File

@ -3,7 +3,7 @@
* Module dependencies.
*/
var MongooseError = require('../error');
var MongooseError = require('../error.js');
/**
* Version Error constructor.
@ -14,15 +14,16 @@ var MongooseError = require('../error');
function VersionError() {
MongooseError.call(this, 'No matching document found.');
Error.captureStackTrace(this, arguments.callee);
Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee);
this.name = 'VersionError';
};
}
/*!
* Inherits from MongooseError.
*/
VersionError.prototype.__proto__ = MongooseError.prototype;
VersionError.prototype = Object.create(MongooseError.prototype);
VersionError.prototype.constructor = MongooseError;
/*!
* exports

View File

@ -1,32 +0,0 @@
/*!
* Module requirements
*/
var MongooseError = require('../error')
/**
* Document Error
*
* @param {String} msg
* @inherits MongooseError
* @api private
*/
function DocumentError (msg) {
MongooseError.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
this.name = 'DocumentError';
};
/*!
* Inherits from MongooseError.
*/
DocumentError.prototype.__proto__ = MongooseError.prototype;
/*!
* Module exports.
*/
module.exports = exports = DocumentError;

View File

@ -1,49 +0,0 @@
/*!
* Module requirements
*/
var MongooseError = require('../error')
/**
* Document Validation Error
*
* @api private
* @param {Document} instance
* @inherits MongooseError
*/
function ValidationError (instance) {
MongooseError.call(this, "Validation failed");
Error.captureStackTrace(this, arguments.callee);
this.name = 'ValidationError';
this.errors = instance.errors = {};
};
/**
* Console.log helper
*/
ValidationError.prototype.toString = function () {
var ret = this.name + ': ';
var msgs = [];
Object.keys(this.errors).forEach(function (key) {
if (this == this.errors[key]) return;
msgs.push(String(this.errors[key]));
}, this)
return ret + msgs.join(', ');
};
/*!
* Inherits from MongooseError.
*/
ValidationError.prototype.__proto__ = MongooseError.prototype;
/*!
* Module exports
*/
module.exports = exports = ValidationError;

View File

@ -1,51 +0,0 @@
/*!
* Module dependencies.
*/
var MongooseError = require('../error');
/**
* Schema validator error
*
* @param {String} path
* @param {String} msg
* @param {String|Number|any} val
* @inherits MongooseError
* @api private
*/
function ValidatorError (path, type, val) {
var msg = type
? '"' + type + '" '
: '';
var message = 'Validator ' + msg + 'failed for path ' + path
if (2 < arguments.length) message += ' with value `' + String(val) + '`';
MongooseError.call(this, message);
Error.captureStackTrace(this, arguments.callee);
this.name = 'ValidatorError';
this.path = path;
this.type = type;
this.value = val;
};
/*!
* toString helper
*/
ValidatorError.prototype.toString = function () {
return this.message;
}
/*!
* Inherits from MongooseError
*/
ValidatorError.prototype.__proto__ = MongooseError.prototype;
/*!
* exports
*/
module.exports = ValidatorError;

185
node_modules/mongoose/lib/index.js generated vendored
View File

@ -1,21 +1,25 @@
'use strict';
/*!
* Module dependencies.
*/
var Schema = require('./schema')
, SchemaType = require('./schematype')
, VirtualType = require('./virtualtype')
, SchemaTypes = Schema.Types
, SchemaDefaults = require('./schemadefault')
, Types = require('./types')
, Query = require('./query')
, Promise = require('./promise')
, Model = require('./model')
, Document = require('./document')
, utils = require('./utils')
, format = utils.toCollectionName
, mongodb = require('mongodb')
var Schema = require('./schema'),
SchemaType = require('./schematype'),
VirtualType = require('./virtualtype'),
STATES = require('./connectionstate'),
Types = require('./types'),
Query = require('./query'),
Model = require('./model'),
Document = require('./document'),
utils = require('./utils'),
format = utils.toCollectionName,
pkg = require('../package.json');
var querystring = require('querystring');
var Aggregate = require('./aggregate');
var PromiseProvider = require('./promise_provider');
/**
* Mongoose constructor.
@ -31,9 +35,19 @@ function Mongoose () {
this.plugins = [];
this.models = {};
this.modelSchemas = {};
this.options = {};
this.createConnection(); // default connection
// default global options
this.options = {
pluralization: true
};
var conn = this.createConnection(); // default connection
conn.models = this.models;
}
/**
* Expose connection states for user-land
*
*/
Mongoose.prototype.STATES = STATES;
/**
* Sets mongoose options
@ -50,8 +64,10 @@ function Mongoose () {
*/
Mongoose.prototype.set = function(key, value) {
if (arguments.length == 1)
if (arguments.length == 1) {
return this.options[key];
}
this.options[key] = value;
return this;
};
@ -76,12 +92,45 @@ Mongoose.prototype.get = Mongoose.prototype.set;
var rgxReplSet = /^.+,.+$/;
/**
* Checks if ?replicaSet query parameter is specified in URI
*
* ####Example:
*
* checkReplicaSetInUri('localhost:27000?replicaSet=rs0'); // true
*
* @param {String} uri
* @return {boolean}
* @api private
*/
var checkReplicaSetInUri = function(uri) {
if (!uri) {
return false;
}
var queryStringStart = uri.indexOf('?');
var isReplicaSet = false;
if (queryStringStart !== -1) {
try {
var obj = querystring.parse(uri.substr(queryStringStart + 1));
if (obj && obj.replicaSet) {
isReplicaSet = true;
}
} catch (e) {
return false;
}
}
return isReplicaSet;
};
/**
* Creates a Connection instance.
*
* Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections.
*
* If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver.
* If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._
*
* _Options passed take precedence over options included in connection strings._
*
@ -95,11 +144,11 @@ var rgxReplSet = /^.+,.+$/;
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
*
* // replica sets
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port');
* db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
*
* // and options
* var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
* db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', opts);
* db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
*
* // with [host, database_name[, port] signature
* db = mongoose.createConnection('localhost', 'database', port)
@ -120,12 +169,15 @@ var rgxReplSet = /^.+,.+$/;
* @api public
*/
Mongoose.prototype.createConnection = function () {
Mongoose.prototype.createConnection = function(uri, options) {
var conn = new Connection(this);
this.connections.push(conn);
if (arguments.length) {
if (rgxReplSet.test(arguments[0])) {
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
conn.openSet.apply(conn, arguments);
} else if (options && options.replset &&
(options.replset.replicaSet || options.replset.rs_name)) {
conn.openSet.apply(conn, arguments);
} else {
conn.open.apply(conn, arguments);
@ -142,6 +194,25 @@ Mongoose.prototype.createConnection = function () {
*
* _Options passed take precedence over options included in connection strings._
*
* ####Example:
*
* mongoose.connect('mongodb://user:pass@localhost:port/database');
*
* // replica sets
* var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase';
* mongoose.connect(uri);
*
* // with options
* mongoose.connect(uri, options);
*
* // connecting to multiple mongos
* var uri = 'mongodb://hostA:27501,hostB:27501';
* var opts = { mongos: true };
* mongoose.connect(uri, opts);
*
* @param {String} uri(s)
* @param {Object} [options]
* @param {Function} [callback]
* @see Mongoose#createConnection #index_Mongoose-createConnection
* @api public
* @return {Mongoose} this
@ -150,7 +221,7 @@ Mongoose.prototype.createConnection = function () {
Mongoose.prototype.connect = function() {
var conn = this.connection;
if (rgxReplSet.test(arguments[0])) {
if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
conn.openSet.apply(conn, arguments);
} else {
conn.open.apply(conn, arguments);
@ -168,8 +239,8 @@ Mongoose.prototype.connect = function () {
*/
Mongoose.prototype.disconnect = function(fn) {
var count = this.connections.length
, error
var count = this.connections.length,
error;
this.connections.forEach(function(conn) {
conn.close(function(err) {
@ -252,13 +323,8 @@ Mongoose.prototype.model = function (name, schema, collection, skipInit) {
options = {};
}
// look up schema for the collection. this might be a
// default schema like system.indexes stored in SchemaDefaults.
// look up schema for the collection.
if (!this.modelSchemas[name]) {
if (!schema && name in SchemaDefaults) {
schema = SchemaDefaults[name];
}
if (schema) {
// cache it so we only apply plugins once
this.modelSchemas[name] = schema;
@ -298,8 +364,12 @@ Mongoose.prototype.model = function (name, schema, collection, skipInit) {
}
}
// Apply relevant "global" options to the schema
if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization;
if (!collection) {
collection = schema.get('collection') || format(name);
collection = schema.get('collection') || format(name, schema.options);
}
var connection = options.connection || this.connection;
@ -314,7 +384,7 @@ Mongoose.prototype.model = function (name, schema, collection, skipInit) {
}
return this.models[name] = model;
}
};
/**
* Returns an array of model names created on this instance of Mongoose.
@ -330,7 +400,7 @@ Mongoose.prototype.model = function (name, schema, collection, skipInit) {
Mongoose.prototype.modelNames = function() {
var names = Object.keys(this.models);
return names;
}
};
/**
* Applies global plugins to `schema`.
@ -343,7 +413,7 @@ Mongoose.prototype._applyPlugins = function (schema) {
for (var i = 0, l = this.plugins.length; i < l; i++) {
schema.plugin(this.plugins[i][0], this.plugins[i][1]);
}
}
};
/**
* Declares a global plugin executed on all Schemas.
@ -400,6 +470,15 @@ var Connection = require(driver + '/connection');
var Collection = require(driver + '/collection');
/**
* The Mongoose Aggregate constructor
*
* @method Aggregate
* @api public
*/
Mongoose.prototype.Aggregate = Aggregate;
/**
* The Mongoose Collection constructor
*
@ -425,7 +504,7 @@ Mongoose.prototype.Connection = Connection;
* @api public
*/
Mongoose.prototype.version = require(__dirname + '/../package.json').version;
Mongoose.prototype.version = pkg.version;
/**
* The Mongoose constructor
@ -533,7 +612,23 @@ Mongoose.prototype.Query = Query;
* @api public
*/
Mongoose.prototype.Promise = Promise;
Object.defineProperty(Mongoose.prototype, 'Promise', {
get: function() {
return PromiseProvider.get();
},
set: function(lib) {
PromiseProvider.set(lib);
}
});
/**
* Storage layer for mongoose promises
*
* @method PromiseProvider
* @api public
*/
Mongoose.prototype.PromiseProvider = PromiseProvider;
/**
* The Mongoose [Model](#model_Model) constructor.
@ -553,6 +648,15 @@ Mongoose.prototype.Model = Model;
Mongoose.prototype.Document = Document;
/**
* The Mongoose DocumentProvider constructor.
*
* @method DocumentProvider
* @api public
*/
Mongoose.prototype.DocumentProvider = require('./document_provider');
/**
* The [MongooseError](#error_MongooseError) constructor.
*
@ -571,6 +675,15 @@ Mongoose.prototype.Error = require('./error');
Mongoose.prototype.mongo = require('mongodb');
/**
* The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
*
* @property mquery
* @api public
*/
Mongoose.prototype.mquery = require('mquery');
/*!
* The exports object is an instance of Mongoose.
*

View File

@ -2,8 +2,8 @@
* Dependencies
*/
var StateMachine = require('./statemachine')
var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default')
var StateMachine = require('./statemachine');
var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore');
module.exports = exports = InternalCache;

1962
node_modules/mongoose/lib/model.js generated vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,70 +0,0 @@
var Query = require('./query');
function NamedScope () {}
NamedScope.prototype.query;
NamedScope.prototype.where = function () {
var q = this.query || (this.query = new Query());
q.where.apply(q, arguments);
return q;
};
/**
* Decorate
*
* @param {NamedScope} target
* @param {Object} getters
* @api private
*/
NamedScope.prototype.decorate = function (target, getters) {
var name = this.name
, block = this.block
, query = this.query;
if (block) {
if (block.length === 0) {
Object.defineProperty(target, name, {
get: getters.block0(block)
});
} else {
target[name] = getters.blockN(block);
}
} else {
Object.defineProperty(target, name, {
get: getters.basic(query)
});
}
};
NamedScope.prototype.compile = function (model) {
var allScopes = this.scopesByName
, scope;
for (var k in allScopes) {
scope = allScopes[k];
scope.decorate(model, {
block0: function (block) {
return function () {
var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
block.call(cquery);
return this;
};
},
blockN: function (block) {
return function () {
var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
block.apply(cquery, arguments);
return this;
};
},
basic: function (query) {
return function () {
var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
cquery.find(query);
return this;
};
}
});
}
};
module.exports = NamedScope;

86
node_modules/mongoose/lib/promise.js generated vendored
View File

@ -1,9 +1,9 @@
/*!
* Module dependencies
*/
var MPromise = require('mpromise');
var util = require('util');
/**
* Promise constructor.
@ -13,28 +13,56 @@ var MPromise = require('mpromise');
* 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
* @inherits mpromise https://github.com/aheckmann/mpromise
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `err`: Emits when the promise is rejected
* @event `complete`: Emits when the promise is fulfilled
* @api public
* @deprecated
*/
function Promise(fn) {
MPromise.call(this, fn);
}
/**
* ES6-style promise constructor wrapper around mpromise.
*
* @param {Function} resolver
* @return {Promise} new promise
* @api public
*/
Promise.ES6 = function(resolver) {
var promise = new Promise();
// No try/catch for backwards compatibility
resolver(
function() {
promise.complete.apply(promise, arguments);
},
function(e) {
promise.error(e);
});
return promise;
};
/*!
* Inherit from mpromise
*/
Promise.prototype = Object.create(MPromise.prototype, {
constructor: {
value: Promise
, enumerable: false
, writable: true
, configurable: true
value: Promise,
enumerable: false,
writable: true,
configurable: true
}
});
@ -85,9 +113,14 @@ Promise.FAILURE = 'err';
*/
Promise.prototype.error = function(err) {
if (!(err instanceof Error)) err = new Error(err);
return this.reject(err);
if (!(err instanceof Error)) {
if (err instanceof Object) {
err = util.inspect(err);
}
err = new Error(err);
}
return this.reject(err);
};
/**
* Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed.
@ -101,12 +134,13 @@ Promise.prototype.error = function (err) {
* @param {Error} [err] error or null
* @param {Object} [val] value to fulfill the promise with
* @api public
* @deprecated
*/
Promise.prototype.resolve = function (err, val) {
Promise.prototype.resolve = function(err) {
if (err) return this.error(err);
return this.fulfill(val);
}
return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1));
};
/**
* Adds a single function as a listener to both err and complete.
@ -120,9 +154,12 @@ Promise.prototype.resolve = function (err, val) {
*
* Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve).
*
* _Deprecated. Use `onResolve` instead._
*
* @method addBack
* @param {Function} listener
* @return {Promise} this
* @deprecated
*/
Promise.prototype.addBack = Promise.prototype.onResolve;
@ -130,11 +167,26 @@ Promise.prototype.addBack = Promise.prototype.onResolve;
/**
* Fulfills this promise with passed arguments.
*
* Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).
*
* @method complete
* @method fulfill
* @receiver Promise
* @see https://github.com/aheckmann/mpromise#fulfill
* @param {any} args
* @api public
* @deprecated
*/
/**
* Fulfills this promise with passed arguments.
*
* Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).
*
* _Deprecated. Use `fulfill` instead._
*
* @method complete
* @receiver Promise
* @param {any} args
* @api public
* @deprecated
*/
Promise.prototype.complete = MPromise.prototype.fulfill;
@ -144,10 +196,13 @@ Promise.prototype.complete = MPromise.prototype.fulfill;
*
* Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill).
*
* _Deprecated. Use `onFulfill` instead._
*
* @method addCallback
* @param {Function} listener
* @return {Promise} this
* @api public
* @deprecated
*/
Promise.prototype.addCallback = Promise.prototype.onFulfill;
@ -157,10 +212,13 @@ Promise.prototype.addCallback = Promise.prototype.onFulfill;
*
* Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject).
*
* _Deprecated. Use `onReject` instead._
*
* @method addErrback
* @param {Function} listener
* @return {Promise} this
* @api public
* @deprecated
*/
Promise.prototype.addErrback = Promise.prototype.onReject;
@ -195,6 +253,7 @@ Promise.prototype.addErrback = Promise.prototype.onReject;
* @param {Function} onFulFill
* @param {Function} onReject
* @return {Promise} newPromise
* @deprecated
*/
/**
@ -222,6 +281,7 @@ Promise.prototype.addErrback = Promise.prototype.onReject;
* @see mpromise#end https://github.com/aheckmann/mpromise#end
* @method end
* @memberOf Promise
* @deprecated
*/
/*!

51
node_modules/mongoose/lib/promise_provider.js generated vendored Normal file
View File

@ -0,0 +1,51 @@
/*!
* Module dependencies.
*/
var MPromise = require('./promise');
/**
* Helper for multiplexing promise implementations
*
* @api private
*/
var Promise = {
_promise: MPromise
};
/**
* Get the current promise constructor
*
* @api private
*/
Promise.get = function() {
return Promise._promise;
};
/**
* Set the current promise constructor
*
* @api private
*/
Promise.set = function(lib) {
if (lib === MPromise) {
return Promise.reset();
}
Promise._promise = require('./ES6Promise');
Promise._promise.use(lib);
require('mquery').Promise = Promise._promise.ES6;
};
/**
* Resets to using mpromise
*
* @api private
*/
Promise.reset = function() {
Promise._promise = MPromise;
};
module.exports = Promise;

3924
node_modules/mongoose/lib/query.js generated vendored

File diff suppressed because it is too large Load Diff

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