Initial commit

This commit is contained in:
Luis Fernando Molina committed 2018-09-03 15:19:57 +02:00
commit f47e08fdcb
2409 files changed
+363607

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
docs/
bin/
test/triage/
test/model.discriminator.test.js
tools/
test/es6/
test/files/
dist/
+12
View File
@@ -0,0 +1,12 @@
<!-- *Before creating an issue please make sure you are using the latest version of mongoose -->
**Do you want to request a *feature* or report a *bug*?**
**What is the current behavior?**
**If the current behavior is a bug, please provide the steps to reproduce.**
<!-- If you can, provide a standalone script / gist to reproduce your issue -->
**What is the expected behavior?**
**Please mention your node.js, mongoose and MongoDB version.**
+9
View File
@@ -0,0 +1,9 @@
<!-- Thanks for submitting a pull request! Please provide enough information so that others can review your pull request. The two fields below are mandatory. -->
**Summary**
<!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? -->
**Test plan**
<!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes UI. -->
+21
View File
@@ -0,0 +1,21 @@
language: node_js
sudo: false
node_js: [10, 9, 8, 7, 6, 5, 4]
install:
- travis_retry npm install
before_script:
- wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.6.6.tgz
- tar -zxvf mongodb-linux-x86_64-3.6.6.tgz
- mkdir -p ./data/db/27017
- mkdir -p ./data/db/27000
- printf "\n--timeout 8000" >> ./test/mocha.opts
- ./mongodb-linux-x86_64-3.6.6/bin/mongod --fork --dbpath ./data/db/27017 --syslog --port 27017
- sleep 2
matrix:
include:
- name: "👕Linter"
node_js: 10
before_script: skip
script: npm run lint
notifications:
email: false
+2
View File
@@ -0,0 +1,2 @@
{
}
+91
View File
@@ -0,0 +1,91 @@
## Contributing to Mongoose
If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), or on [Gitter](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
### Reporting bugs
- Before opening a new issue, look for existing [issues](https://github.com/Automattic/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/Automattic/mongoose/issues/new).
- Please post any relevant code samples, preferably a standalone script that
reproduces your issue. Do **not** describe your issue in prose, show your
code.
- If the bug involves an error, please post the stack trace.
- Please post the version of mongoose and mongodb that you're using.
 - Please write bug reports in JavaScript (ES5, ES6, etc) that runs in Node.js, not coffeescript, typescript, etc.
### Requesting new features
- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new).
- Please describe a use case for it
- it would be ideal to include test cases as well
### Fixing bugs / Adding features
- Before starting to write code, look for existing [issues](https://github.com/learnboost/mongoose/issues). That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. You can create a new issue [here](https://github.com/learnboost/mongoose/issues/new).
- _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_.
- Fork the [repo](https://github.com/Automattic/mongoose) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
- Follow the general coding style of the rest of the project:
- 2 space tabs
- no trailing whitespace
- inline documentation for new methods, class members, etc.
- 1 space between conditionals, no space before function parenthesis
- `if (..) {`
- `for (..) {`
- `while (..) {`
- `function(err) {`
- Write tests and make sure they pass (tests are in the [test](https://github.com/Automattic/mongoose/tree/master/test) directory).
### Running the tests
- Open a terminal and navigate to the root of the project
- execute `npm install` to install the necessary dependencies
- start a mongodb instance on port 27017 if one isn't running already. `mongod --dbpath <path to store data> --port 27017 --storageEngine mmapv1`. Mongoose tests run much faster on the mmapv1 storage engine as opposed to the WiredTiger storage engine.
- execute `npm test` to run the tests (we're using [mocha](http://mochajs.org/))
- or to execute a single test `npm test -- -g 'some regexp that matches the test description'`
- any mocha flags can be specified with `-- <mocha flags here>`
- For example, you can use `npm test -- -R spec` to use the spec reporter, rather than the dot reporter (by default, the test output looks like a bunch of dots)
### Documentation
To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/Automattic/mongoose/tree/master/lib) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/Automattic/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here.
If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute:
* `make docclean`
* `make gendocs`
* `node static.js`
Visit `http://localhost:8088` and you should see the docs with your local changes. Make sure you `git reset --hard` before commiting, because changes to `docs/*` should **not** be in PRs.
### Plugins website
The [plugins](http://plugins.mongoosejs.io/) site is also an [open source project](https://github.com/vkarpov15/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well!
## Financial contributions
We also welcome financial contributions in full transparency on our [open collective](https://opencollective.com/mongoose).
Anyone can file an expense. If the expense makes sense for the development of the community, it will be "merged" in the ledger of our open collective by the core contributors and the person who filed the expense will be reimbursed.
## Credits
### Contributors
Thank you to all the people who have already contributed to mongoose!
<a href="graphs/contributors"><img src="https://opencollective.com/mongoose/contributors.svg?width=890" /></a>
### Backers
Thank you to all our backers! [[Become a backer](https://opencollective.com/mongoose#backer)]
<a href="https://opencollective.com/mongoose#backers" target="_blank"><img src="https://opencollective.com/mongoose/backers.svg?width=890"></a>
### Sponsors
Thank you to all our sponsors! (please ask your company to also support this open source project by [becoming a sponsor](https://opencollective.com/mongoose#sponsor))
<a href="https://mixmax.com" target="_blank"><img src="http://mongoosejs.com/docs/images/mixmax.png"></a>
+4541
View File
File diff suppressed because it is too large. Load diff
+332
View File
@@ -0,0 +1,332 @@
# Mongoose
Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment.
[![Slack Status](http://slack.mongoosejs.io/badge.svg)](http://slack.mongoosejs.io)
[![Build Status](https://api.travis-ci.org/Automattic/mongoose.svg?branch=master)](https://travis-ci.org/Automattic/mongoose)
[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose)
[![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose)
## Documentation
[mongoosejs.com](http://mongoosejs.com/)
[Mongoose 5.0.0](https://github.com/Automattic/mongoose/blob/master/History.md#500--2018-01-17) was released on January 17, 2018. You can find more details on backwards breaking changes in 5.0.0 on [GitHub](https://github.com/Automattic/mongoose/blob/master/migrating_to_5.md).
## Support
- [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose)
- [Bug Reports](https://github.com/Automattic/mongoose/issues/)
- [Mongoose Slack Channel](http://slack.mongoosejs.io/)
- [Help Forum](http://groups.google.com/group/mongoose-orm)
- [MongoDB Support](https://docs.mongodb.org/manual/support/)
## Importing
```javascript
// Using Node.js `require()`
const mongoose = require('mongoose');
// Using ES6 imports
import mongoose from 'mongoose';
```
## Plugins
Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins).
## Contributors
Pull requests are always welcome! Please base pull requests against the `master`
branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md).
If your pull requests makes documentation changes, please do **not**
modify any `.html` files. The `.html` files are compiled code, so please make
your changes in `docs/*.jade`, `lib/*.js`, or `test/docs/*.js`.
View all 300+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).
## Installation
First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then:
```sh
$ npm install mongoose
```
## Overview
### Connecting to MongoDB
First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.
Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.
```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
```
Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`.
**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._
**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.
### Defining a Model
Models are defined through the `Schema` interface.
```js
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const BlogPost = new Schema({
author: ObjectId,
title: String,
body: String,
  date: Date
});
```
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync)
* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default)
* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get)
* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set)
* [Indexes](http://mongoosejs.com/docs/guide.html#indexes)
* [Middleware](http://mongoosejs.com/docs/middleware.html)
* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition
* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition
* [Plugins](http://mongoosejs.com/docs/plugins.html)
* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html)
The following example shows some of these features:
```js
const Comment = new Schema({
name: { type: String, default: 'hahaha' },
age: { type: Number, min: 18, index: true },
bio: { type: String, match: /[a-z]/ },
date: { type: Date, default: Date.now },
buff: Buffer
});
// a setter
Comment.path('name').set(function (v) {
return capitalize(v);
});
// middleware
Comment.pre('save', function (next) {
notify(this.get('email'));
next();
});
```
Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
### Accessing a Model
Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function
```js
const myModel = mongoose.model('ModelName');
```
Or just do it all at once
```js
const MyModel = mongoose.model('ModelName', mySchema);
```
The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use
```js
const 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
const instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
//
});
```
Or we can find documents from the same collection
```js
MyModel.find({}, function (err, docs) {
// docs.forEach
});
```
You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html).
**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:
```js
const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model('ModelName', schema);
const m = new MyModel;
m.save(); // works
```
vs
```js
const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const 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: [Comment]
```
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');
// create a blog post
var post = new BlogPost();
// create a comment
post.comments.push({ title: 'My comment' });
post.save(function (err) {
if (!err) console.log('Success!');
});
```
The same goes for removing them:
```js
BlogPost.findById(myId, function (err, post) {
if (!err) {
post.comments[0].remove();
post.save(function (err) {
// do something
});
}
});
```
Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap!
### Middleware
See the [docs](http://mongoosejs.com/docs/middleware.html) page.
#### Intercepting and mutating method arguments
You can intercept method arguments via middleware.
For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value:
```js
schema.pre('set', function (next, path, val, typel) {
// `this` is the current Document
this.emit('set', path, val);
// Pass control to the next pre
next();
});
```
Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`:
```js
.pre(method, function firstPre (next, methodArg1, methodArg2) {
// Mutate methodArg1
next("altered-" + methodArg1.toString(), methodArg2);
});
// pre declaration is chainable
.pre(method, function secondPre (next, methodArg1, methodArg2) {
console.log(methodArg1);
// => 'altered-originalValOfMethodArg1'
console.log(methodArg2);
// => 'originalValOfMethodArg2'
// Passing no arguments to `next` automatically passes along the current argument values
// i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
// and also equivalent to, with the example method arg
// values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
next();
});
```
#### Schema gotcha
`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation:
```js
new Schema({
broken: { type: Boolean },
asset: {
name: String,
type: String // uh oh, it broke. asset will be interpreted as String
}
});
new Schema({
works: { type: Boolean },
asset: {
name: String,
type: { type: String } // works. asset is an object with a type property
}
});
```
### Driver Access
Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one
notable exception that `YourModel.collection` still buffers
commands. As such, `YourModel.collection.find()` will **not**
return a cursor.
## API Docs
Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox)
and [acquit](https://github.com/vkarpov15/acquit).
## License
Copyright (c) 2010 LearnBoost &lt;dev@learnboost.com&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+8
View File
@@ -0,0 +1,8 @@
/**
* Export lib/mongoose
*
*/
'use strict';
module.exports = require('./lib/browser');
+41
View File
@@ -0,0 +1,41 @@
This directory contains runnable sample mongoose programs.
To run:
- first install [Node.js](http://nodejs.org/)
- from the root of the project, execute `npm install -d`
- in the example directory, run `npm install -d`
- from the command line, execute: `node example.js`, replacing "example.js" with the name of a program.
Goal is to show:
- ~~global schemas~~
- ~~GeoJSON schemas / use (with crs)~~
- text search (once MongoDB removes the "Experimental/beta" label)
- ~~lean queries~~
- ~~statics~~
- methods and statics on subdocs
- custom types
- ~~querybuilder~~
- ~~promises~~
- accessing driver collection, db
- ~~connecting to replica sets~~
- connecting to sharded clusters
- enabling a fail fast mode
- on the fly schemas
- storing files
- ~~map reduce~~
- ~~aggregation~~
- advanced hooks
- using $elemMatch to return a subset of an array
- query casting
- upserts
- pagination
- express + mongoose session handling
- ~~group by (use aggregation)~~
- authentication
- schema migration techniques
- converting documents to plain objects (show transforms)
- how to $unset
+105
View File
@@ -0,0 +1,105 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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
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"
}
+19
View File
@@ -0,0 +1,19 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date,
gender: String,
likes: [String]
});
mongoose.model('Person', PersonSchema);
};
+78
View File
@@ -0,0 +1,78 @@
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Schema
*/
const CharacterSchema = Schema({
name: {
type: String,
required: true
},
health: {
type: Number,
min: 0,
max: 100
}
});
/**
* Methods
*/
CharacterSchema.methods.attack = function() {
console.log('%s is attacking', this.name);
};
/**
* Character model
*/
const Character = mongoose.model('Character', CharacterSchema);
/**
* Connect to the database on localhost with
* the default port (27017)
*/
const dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0);
const uri = 'mongodb://localhost/' + dbname;
console.log('connecting to %s', uri);
mongoose.connect(uri, function(err) {
// if we failed to connect, abort
if (err) throw err;
// we connected ok
example();
});
/**
* Use case
*/
function example() {
Character.create({name: 'Link', health: 100}, function(err, link) {
if (err) return done(err);
console.log('found', link);
link.attack(); // 'Link is attacking'
done();
});
}
/**
* Clean up
*/
function done(err) {
if (err) console.error(err);
mongoose.connection.db.dropDatabase(function() {
mongoose.disconnect();
});
}
+1
View File
@@ -0,0 +1 @@
Mongoose + Express examples
@@ -0,0 +1,6 @@
To run:
- Execute `npm install` from this directory
- Execute `node app.js`
- Navigate to `localhost:8000`
@@ -0,0 +1,18 @@
'use strict';
const express = require('express');
const mongoose = require('../../../lib');
const uri = 'mongodb://localhost/mongoose-shared-connection';
global.db = mongoose.createConnection(uri);
const routes = require('./routes');
const 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');
});
@@ -0,0 +1,6 @@
'use strict';
const Schema = require('../../../lib').Schema;
const mySchema = Schema({name: String});
/* global db */
module.exports = db.model('MyModel', mySchema);
@@ -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"
}
@@ -0,0 +1,21 @@
'use strict';
const 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);
});
};
+24
View File
@@ -0,0 +1,24 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const 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
const LocationObject = new Schema({
loc: {
type: {type: String},
coordinates: []
}
});
// define the index
LocationObject.index({loc: '2dsphere'});
mongoose.model('Location', LocationObject);
};
+58
View File
@@ -0,0 +1,58 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./geoJSONSchema.js')();
const Location = mongoose.model('Location');
// define some dummy data
// note: the type can be Point, LineString, or Polygon
const 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
const 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();
});
}
+102
View File
@@ -0,0 +1,102 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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/
const 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
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"
}
+29
View File
@@ -0,0 +1,29 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const 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);
};
+48
View File
@@ -0,0 +1,48 @@
'use strict';
const 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
const 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();
});
}
+16
View File
@@ -0,0 +1,16 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};
+86
View File
@@ -0,0 +1,86 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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)
const 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
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"
}
+18
View File
@@ -0,0 +1,18 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date,
gender: String,
likes: [String]
});
mongoose.model('Person', PersonSchema);
};
+102
View File
@@ -0,0 +1,102 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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
const 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
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"
}
+18
View File
@@ -0,0 +1,18 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date,
gender: String
});
mongoose.model('Person', PersonSchema);
};
@@ -0,0 +1,135 @@
'use strict';
const assert = require('assert');
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
const ObjectId = mongoose.Types.ObjectId;
/**
* Connect to the db
*/
const dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random();
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function() {
console.error('connection error', arguments);
});
/**
* Schemas
*/
const user = new Schema({
name: String,
friends: [{
type: Schema.ObjectId,
ref: 'User'
}]
});
const User = mongoose.model('User', user);
const blogpost = Schema({
title: String,
tags: [String],
author: {
type: Schema.ObjectId,
ref: 'User'
}
});
const BlogPost = mongoose.model('BlogPost', blogpost);
/**
* example
*/
mongoose.connection.on('open', function() {
/**
* Generate data
*/
const userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId];
const users = [];
users.push({
_id: userIds[0],
name: 'mary',
friends: [userIds[1], userIds[2], userIds[3]]
});
users.push({
_id: userIds[1],
name: 'bob',
friends: [userIds[0], userIds[2], userIds[3]]
});
users.push({
_id: userIds[2],
name: 'joe',
friends: [userIds[0], userIds[1], userIds[3]]
});
users.push({
_id: userIds[3],
name: 'sally',
friends: [userIds[0], userIds[1], userIds[2]]
});
User.create(users, function(err) {
assert.ifError(err);
const blogposts = [];
blogposts.push({
title: 'blog 1',
tags: ['fun', 'cool'],
author: userIds[3]
});
blogposts.push({
title: 'blog 2',
tags: ['cool'],
author: userIds[1]
});
blogposts.push({
title: 'blog 3',
tags: ['fun', 'odd'],
author: userIds[2]
});
BlogPost.create(blogposts, function(err) {
assert.ifError(err);
/**
* Population
*/
BlogPost
.find({tags: 'fun'})
.lean()
.populate('author')
.exec(function(err, docs) {
assert.ifError(err);
/**
* Populate the populated documents
*/
const opts = {
path: 'author.friends',
select: 'name',
options: {limit: 2}
};
BlogPost.populate(docs, opts, function(err, docs) {
assert.ifError(err);
console.log('populated');
const s = require('util').inspect(docs, {depth: null, colors: true});
console.log(s);
done();
});
});
});
});
});
function done(err) {
if (err) console.error(err.stack);
mongoose.connection.db.dropDatabase(function() {
mongoose.connection.close();
});
}
+104
View File
@@ -0,0 +1,104 @@
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Console schema
*/
const consoleSchema = Schema({
name: String,
manufacturer: String,
released: Date
});
const Console = mongoose.model('Console', consoleSchema);
/**
* Game schema
*/
const gameSchema = Schema({
name: String,
developer: String,
released: Date,
consoles: [{
type: Schema.Types.ObjectId,
ref: 'Console'
}]
});
const Game = mongoose.model('Game', gameSchema);
/**
* Connect to the console database on localhost with
* the default port (27017)
*/
mongoose.connect('mongodb://localhost/console', function(err) {
// if we failed to connect, abort
if (err) throw err;
// we connected ok
createData();
});
/**
* Data generation
*/
function createData() {
Console.create(
{
name: 'Nintendo 64',
manufacturer: 'Nintendo',
released: 'September 29, 1996'
},
function(err, nintendo64) {
if (err) return done(err);
Game.create({
name: 'Legend of Zelda: Ocarina of Time',
developer: 'Nintendo',
released: new Date('November 21, 1998'),
consoles: [nintendo64]
},
function(err) {
if (err) return done(err);
example();
});
}
);
}
/**
* Population
*/
function example() {
Game
.findOne({name: /^Legend of Zelda/})
.populate('consoles')
.exec(function(err, ocinara) {
if (err) return done(err);
console.log(
'"%s" was released for the %s on %s',
ocinara.name,
ocinara.consoles[0].name,
ocinara.released.toLocaleDateString()
);
done();
});
}
function done(err) {
if (err) console.error(err);
Console.remove(function() {
Game.remove(function() {
mongoose.disconnect();
});
});
}
@@ -0,0 +1,110 @@
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Console schema
*/
const consoleSchema = Schema({
name: String,
manufacturer: String,
released: Date
});
const Console = mongoose.model('Console', consoleSchema);
/**
* Game schema
*/
const gameSchema = Schema({
name: String,
developer: String,
released: Date,
consoles: [{
type: Schema.Types.ObjectId,
ref: 'Console'
}]
});
const Game = mongoose.model('Game', gameSchema);
/**
* Connect to the console database on localhost with
* the default port (27017)
*/
mongoose.connect('mongodb://localhost/console', function(err) {
// if we failed to connect, abort
if (err) throw err;
// we connected ok
createData();
});
/**
* Data generation
*/
function createData() {
Console.create(
{
name: 'Nintendo 64',
manufacturer: 'Nintendo',
released: 'September 29, 1996'
},
function(err, nintendo64) {
if (err) return done(err);
Game.create({
name: 'Legend of Zelda: Ocarina of Time',
developer: 'Nintendo',
released: new Date('November 21, 1998'),
consoles: [nintendo64]
},
function(err) {
if (err) return done(err);
example();
});
}
);
}
/**
* Population
*/
function example() {
Game
.findOne({name: /^Legend of Zelda/})
.exec(function(err, ocinara) {
if (err) return done(err);
console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]);
// population of existing document
ocinara.populate('consoles', function(err) {
if (err) return done(err);
console.log(
'"%s" was released for the %s on %s',
ocinara.name,
ocinara.consoles[0].name,
ocinara.released.toLocaleDateString()
);
done();
});
});
}
function done(err) {
if (err) console.error(err);
Console.remove(function() {
Game.remove(function() {
mongoose.disconnect();
});
});
}
@@ -0,0 +1,125 @@
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Console schema
*/
const consoleSchema = Schema({
name: String,
manufacturer: String,
released: Date
});
const Console = mongoose.model('Console', consoleSchema);
/**
* Game schema
*/
const gameSchema = Schema({
name: String,
developer: String,
released: Date,
consoles: [{
type: Schema.Types.ObjectId,
ref: 'Console'
}]
});
const 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);
const 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();
});
});
}
+139
View File
@@ -0,0 +1,139 @@
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Console schema
*/
const consoleSchema = Schema({
name: String,
manufacturer: String,
released: Date
});
const Console = mongoose.model('Console', consoleSchema);
/**
* Game schema
*/
const gameSchema = Schema({
name: String,
developer: String,
released: Date,
consoles: [{
type: Schema.Types.ObjectId,
ref: 'Console'
}]
});
const Game = mongoose.model('Game', gameSchema);
/**
* Connect to the console database on localhost with
* the default port (27017)
*/
mongoose.connect('mongodb://localhost/console', function(err) {
// if we failed to connect, abort
if (err) throw err;
// we connected ok
createData();
});
/**
* Data generation
*/
function createData() {
Console.create(
{
name: 'Nintendo 64',
manufacturer: 'Nintendo',
released: 'September 29, 1996'
},
{
name: 'Super Nintendo',
manufacturer: 'Nintendo',
released: 'August 23, 1991'
},
{
name: 'XBOX 360',
manufacturer: 'Microsoft',
released: 'November 22, 2005'
},
function(err, nintendo64, superNintendo, xbox360) {
if (err) return done(err);
Game.create(
{
name: 'Legend of Zelda: Ocarina of Time',
developer: 'Nintendo',
released: new Date('November 21, 1998'),
consoles: [nintendo64]
},
{
name: 'Mario Kart',
developer: 'Nintendo',
released: 'September 1, 1992',
consoles: [superNintendo]
},
{
name: 'Perfect Dark Zero',
developer: 'Rare',
released: 'November 17, 2005',
consoles: [xbox360]
},
function(err) {
if (err) return done(err);
example();
}
);
}
);
}
/**
* Population
*/
function example() {
Game
.find({})
.populate({
path: 'consoles',
match: {manufacturer: 'Nintendo'},
select: 'name',
options: {comment: 'population'}
})
.exec(function(err, games) {
if (err) return done(err);
games.forEach(function(game) {
console.log(
'"%s" was released for the %s on %s',
game.name,
game.consoles.length ? game.consoles[0].name : '??',
game.released.toLocaleDateString()
);
});
return done();
});
}
/**
* Clean up
*/
function done(err) {
if (err) console.error(err);
Console.remove(function() {
Game.remove(function() {
mongoose.disconnect();
});
});
}
@@ -0,0 +1,107 @@
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
console.log('Running mongoose version %s', mongoose.version);
/**
* Console schema
*/
const consoleSchema = Schema({
name: String,
manufacturer: String,
released: Date
});
const Console = mongoose.model('Console', consoleSchema);
/**
* Game schema
*/
const gameSchema = Schema({
name: String,
developer: String,
released: Date,
consoles: [{
type: Schema.Types.ObjectId,
ref: 'Console'
}]
});
const 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
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"
}
+17
View File
@@ -0,0 +1,17 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};
+96
View File
@@ -0,0 +1,96 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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)
const 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
const ids = people.map(function(p) {
return p._id;
});
// return the next promise
return Person.find({_id: {$nin: ids}}).exec();
}).then(function(oldest) {
console.log('Oldest person is: %s', oldest);
}).then(cleanup);
});
});
function cleanup() {
Person.remove(function() {
mongoose.disconnect();
});
}
+14
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"
}
+17
View File
@@ -0,0 +1,17 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};
+81
View File
@@ -0,0 +1,81 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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
const query = Person.find({age: {$lt: 1000}});
// this allows you to continue applying modifiers to it
query.sort('birthday');
query.select('name');
// you can chain them together as well
// a full list of methods can be found:
// http://mongoosejs.com/docs/api.html#query-js
query.where('age').gt(21);
// finally, when ready to execute the query, call the exec() function
query.exec(function(err, results) {
if (err) throw err;
console.log(results);
cleanup();
});
});
});
function cleanup() {
Person.remove(function() {
mongoose.disconnect();
});
}
+14
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"
}
+17
View File
@@ -0,0 +1,17 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const PersonSchema = new Schema({
name: String,
age: Number,
birthday: Date
});
mongoose.model('Person', PersonSchema);
};
+73
View File
@@ -0,0 +1,73 @@
// import async to make control flow simplier
'use strict';
const async = require('async');
// import the rest of the normal stuff
const mongoose = require('../../lib');
require('./person.js')();
const Person = mongoose.model('Person');
// define some dummy data
const 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.
const 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
const 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();
});
}
+120
View File
@@ -0,0 +1,120 @@
/**
* Module dependencies.
*/
'use strict';
let mongoose = require('../../lib'), Schema = mongoose.Schema;
/**
* Schema definition
*/
// recursive embedded-document schema
const Comment = new Schema();
Comment.add({
title: {
type: String,
index: true
},
date: Date,
body: String,
comments: [Comment]
});
const BlogPost = new Schema({
title: {
type: String,
index: true
},
slug: {
type: String,
lowercase: true,
trim: true
},
date: Date,
buf: Buffer,
comments: [Comment],
creator: Schema.ObjectId
});
const 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 || {};
const 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);
@@ -0,0 +1,29 @@
// modules
'use strict';
const mongoose = require('../../../lib');
const Schema = mongoose.Schema;
// parse json
const raw = require('./schema.json');
// create a schema
const timeSignatureSchema = Schema(raw);
// compile the model
const TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema);
// create a TimeSignature document
const 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);
@@ -0,0 +1,9 @@
{
"count": "number",
"unit": "number",
"description": "string",
"links": ["string"],
"created": "date",
"additive": "boolean",
"user_id": "ObjectId"
}
+22
View File
@@ -0,0 +1,22 @@
// import the necessary modules
'use strict';
const mongoose = require('../../lib');
const Schema = mongoose.Schema;
// create an export function to encapsulate the model creation
module.exports = function() {
// define schema
const 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);
};
+42
View File
@@ -0,0 +1,42 @@
'use strict';
const mongoose = require('../../lib');
// import the schema
require('./person.js')();
// grab the person model object
const 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();
});
}
+9
View File
@@ -0,0 +1,9 @@
/**
* Export lib/mongoose
*
*/
'use strict';
module.exports = require('./lib/');
+1027
View File
File diff suppressed because it is too large. Load diff
+133
View File
@@ -0,0 +1,133 @@
/* eslint-env browser */
'use strict';
require('./driver').set(require('./drivers/browser'));
const DocumentProvider = require('./document_provider.js');
const PromiseProvider = require('./promise_provider');
DocumentProvider.setBrowser(true);
/**
* The Mongoose [Promise](#promise_Promise) constructor.
*
* @method Promise
* @api public
*/
Object.defineProperty(exports, 'Promise', {
get: function() {
return PromiseProvider.get();
},
set: function(lib) {
PromiseProvider.set(lib);
}
});
/**
* Storage layer for mongoose promises
*
* @method PromiseProvider
* @api public
*/
exports.PromiseProvider = PromiseProvider;
/**
* 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 = DocumentProvider();
/*!
* Module exports.
*/
if (typeof window !== 'undefined') {
window.mongoose = module.exports;
window.Buffer = Buffer;
}
+96
View File
@@ -0,0 +1,96 @@
/*!
* Module dependencies.
*/
'use strict';
const NodeJSDocument = require('./document');
const EventEmitter = require('events').EventEmitter;
const MongooseError = require('./error');
const Schema = require('./schema');
const ObjectId = require('./types/objectid');
const ValidationError = MongooseError.ValidationError;
const applyHooks = require('./helpers/model/applyHooks');
const utils = require('./utils');
/**
* Document constructor.
*
* @param {Object} obj the values to set
* @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
* @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose.
* @event `save`: Emitted when the document is successfully saved
* @api private
*/
function Document(obj, schema, fields, skipId, skipInit) {
if (!(this instanceof Document)) {
return new Document(obj, schema, fields, skipId, skipInit);
}
if (utils.isObject(schema) && !schema.instanceOfSchema) {
schema = new Schema(schema);
}
// When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
schema = this.schema || schema;
// Generate ObjectId if it is missing, but it requires a scheme
if (!this.schema && schema.options._id) {
obj = obj || {};
if (obj._id === undefined) {
obj._id = new ObjectId();
}
}
if (!schema) {
throw new MongooseError.MissingSchemaError();
}
this.$__setSchema(schema);
NodeJSDocument.call(this, obj, fields, skipId, skipInit);
applyHooks(this, schema, { decorateDoc: true });
// apply methods
for (const m in schema.methods) {
this[m] = schema.methods[m];
}
// apply statics
for (const s in schema.statics) {
this[s] = schema.statics[s];
}
}
/*!
* Inherit from the NodeJS document
*/
Document.prototype = Object.create(NodeJSDocument.prototype);
Document.prototype.constructor = Document;
/*!
* Browser doc exposes the event emitter API
*/
Document.$emitter = new EventEmitter();
utils.each(
['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
'removeAllListeners', 'addListener'],
function(emitterFn) {
Document[emitterFn] = function() {
return Document.$emitter[emitterFn].apply(Document.$emitter, arguments);
};
});
/*!
* Module exports.
*/
Document.ValidationError = ValidationError;
module.exports = exports = Document;
+336
View File
@@ -0,0 +1,336 @@
'use strict';
/*!
* Module dependencies.
*/
const StrictModeError = require('./error/strict');
const Types = require('./schema/index');
const castTextSearch = require('./schema/operators/text');
const get = require('lodash.get');
const util = require('util');
const utils = require('./utils');
const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
/**
* Handles internal casting for query filters.
*
* @param {Schema} schema
* @param {Object} obj Object to cast
* @param {Object} options the query options
* @param {Query} context passed to setters
* @api private
*/
module.exports = function cast(schema, obj, options, context) {
if (Array.isArray(obj)) {
throw new Error('Query filter must be an object, got an array ', util.inspect(obj));
}
const paths = Object.keys(obj);
let i = paths.length;
let _keys;
let any$conditionals;
let schematype;
let nested;
let path;
let type;
let val;
options = options || {};
while (i--) {
path = paths[i];
val = obj[path];
if (path === '$or' || path === '$nor' || path === '$and') {
var k = val.length;
while (k--) {
val[k] = cast(schema, val[k], options, context);
}
} else if (path === '$where') {
type = typeof val;
if (type !== 'string' && type !== 'function') {
throw new Error('Must have a string or function for $where');
}
if (type === 'function') {
obj[path] = val.toString();
}
continue;
} else if (path === '$elemMatch') {
val = cast(schema, val, options, context);
} else if (path === '$text') {
val = castTextSearch(val, path);
} else {
if (!schema) {
// no casting for Mixed types
continue;
}
schematype = schema.path(path);
// Check for embedded discriminator paths
if (!schematype) {
const split = path.split('.');
let j = split.length;
while (j--) {
const pathFirstHalf = split.slice(0, j).join('.');
const pathLastHalf = split.slice(j).join('.');
const _schematype = schema.path(pathFirstHalf);
const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey');
// gh-6027: if we haven't found the schematype but this path is
// underneath an embedded discriminator and the embedded discriminator
// key is in the query, use the embedded discriminator schema
if (_schematype != null &&
get(_schematype, 'schema.discriminators') != null &&
discriminatorKey != null &&
pathLastHalf !== discriminatorKey) {
const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
if (discriminatorVal) {
schematype = _schematype.schema.discriminators[discriminatorVal].
path(pathLastHalf);
}
}
}
}
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, options, context)[pathLastHalf];
} else {
obj[path] = val;
}
continue;
}
if (utils.isObject(val)) {
// handle geo schemas that use object notation
// { loc: { long: Number, lat: Number }
let geo = '';
if (val.$near) {
geo = '$near';
} else if (val.$nearSphere) {
geo = '$nearSphere';
} else if (val.$within) {
geo = '$within';
} else if (val.$geoIntersects) {
geo = '$geoIntersects';
} else if (val.$geoWithin) {
geo = '$geoWithin';
}
if (geo) {
const numbertype = new Types.Number('__QueryCasting__');
let value = val[geo];
if (val.$maxDistance != null) {
val.$maxDistance = numbertype.castForQueryWrapper({
val: val.$maxDistance,
context: context
});
}
if (val.$minDistance != null) {
val.$minDistance = numbertype.castForQueryWrapper({
val: val.$minDistance,
context: context
});
}
if (geo === '$within') {
const withinType = value.$center
|| value.$centerSphere
|| value.$box
|| value.$polygon;
if (!withinType) {
throw new Error('Bad $within parameter: ' + JSON.stringify(val));
}
value = withinType;
} else if (geo === '$near' &&
typeof value.type === 'string' && Array.isArray(value.coordinates)) {
// geojson; cast the coordinates
value = value.coordinates;
} else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') &&
value.$geometry && typeof value.$geometry.type === 'string' &&
Array.isArray(value.$geometry.coordinates)) {
if (value.$maxDistance != null) {
value.$maxDistance = numbertype.castForQueryWrapper({
val: value.$maxDistance,
context: context
});
}
if (value.$minDistance != null) {
value.$minDistance = numbertype.castForQueryWrapper({
val: value.$minDistance,
context: context
});
}
if (utils.isMongooseObject(value.$geometry)) {
value.$geometry = value.$geometry.toObject({
transform: false,
virtuals: false
});
}
value = value.$geometry.coordinates;
} else if (geo === '$geoWithin') {
if (value.$geometry) {
if (utils.isMongooseObject(value.$geometry)) {
value.$geometry = value.$geometry.toObject({ virtuals: false });
}
const geoWithinType = value.$geometry.type;
if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) {
throw new Error('Invalid geoJSON type for $geoWithin "' +
geoWithinType + '", must be "Polygon" or "MultiPolygon"');
}
value = value.$geometry.coordinates;
} else {
value = value.$box || value.$polygon || value.$center ||
value.$centerSphere;
if (utils.isMongooseObject(value)) {
value = value.toObject({ virtuals: false });
}
}
}
_cast(value, numbertype, context);
continue;
}
}
if (options.upsert && options.strict && !schema.nested[path]) {
if (options.strict === 'throw') {
throw new StrictModeError(path);
}
throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
'schema, strict mode is `true`, and upsert is `true`.');
} else if (options.strictQuery === 'throw') {
throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
'schema and strictQuery is true.');
} else if (options.strictQuery) {
delete obj[path];
}
} else if (val == null) {
continue;
} else if (val.constructor.name === 'Object') {
any$conditionals = Object.keys(val).some(function(k) {
return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
});
if (!any$conditionals) {
obj[path] = schematype.castForQueryWrapper({
val: val,
context: context
});
} else {
var ks = Object.keys(val),
$cond;
k = ks.length;
while (k--) {
$cond = ks[k];
nested = val[$cond];
if ($cond === '$not') {
if (nested && schematype && !schematype.caster) {
_keys = Object.keys(nested);
if (_keys.length && _keys[0].charAt(0) === '$') {
for (const key in nested) {
nested[key] = schematype.castForQueryWrapper({
$conditional: key,
val: nested[key],
context: context
});
}
} else {
val[$cond] = schematype.castForQueryWrapper({
$conditional: $cond,
val: nested,
context: context
});
}
continue;
}
cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context);
} else {
val[$cond] = schematype.castForQueryWrapper({
$conditional: $cond,
val: nested,
context: context
});
}
}
}
} else if (val.constructor.name === 'Array' && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) {
const casted = [];
for (let valIndex = 0; valIndex < val.length; valIndex++) {
casted.push(schematype.castForQueryWrapper({
val: val[valIndex],
context: context
}));
}
obj[path] = { $in: casted };
} else {
obj[path] = schematype.castForQueryWrapper({
val: val,
context: context
});
}
}
}
return obj;
};
function _cast(val, numbertype, context) {
if (Array.isArray(val)) {
val.forEach(function(item, i) {
if (Array.isArray(item) || utils.isObject(item)) {
return _cast(item, numbertype, context);
}
val[i] = numbertype.castForQueryWrapper({ val: item, context: context });
});
} else {
const nearKeys = Object.keys(val);
let nearLen = nearKeys.length;
while (nearLen--) {
const nkey = nearKeys[nearLen];
const item = val[nkey];
if (Array.isArray(item) || utils.isObject(item)) {
_cast(item, numbertype, context);
val[nkey] = item;
} else {
val[nkey] = numbertype.castForQuery({ val: item, context: context });
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
'use strict';
const CastError = require('../error/cast');
/*!
* Given a value, cast it to a boolean, or throw a `CastError` if the value
* cannot be casted. `null` and `undefined` are considered valid.
*
* @param {Any} value
* @param {String} [path] optional the path to set on the CastError
* @return {Boolean|null|undefined}
* @throws {CastError} if `value` is not one of the allowed values
* @api private
*/
module.exports = function castBoolean(value, path) {
if (value == null) {
return value;
}
if (module.exports.convertToTrue.has(value)) {
return true;
}
if (module.exports.convertToFalse.has(value)) {
return false;
}
throw new CastError('boolean', value, path);
};
module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']);
module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']);
+49
View File
@@ -0,0 +1,49 @@
'use strict';
const CastError = require('../error/cast');
/*!
* Given a value, cast it to a number, or throw a `CastError` if the value
* cannot be casted. `null` and `undefined` are considered valid.
*
* @param {Any} value
* @param {String} [path] optional the path to set on the CastError
* @return {Boolean|null|undefined}
* @throws {CastError} if `value` is not one of the allowed values
* @api private
*/
module.exports = function castNumber(val, path) {
if (isNaN(val)) {
throw new CastError('number', val, path);
}
if (val == null) {
return val;
}
if (val === '') {
return null;
}
if (typeof val === 'string' || typeof val === 'boolean') {
val = Number(val);
}
if (isNaN(val)) {
throw new CastError('number', val, path);
}
if (val instanceof Number) {
return val;
}
if (typeof val === 'number') {
return val;
}
if (!Array.isArray(val) && typeof val.valueOf === 'function') {
return Number(val.valueOf());
}
if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) {
return new Number(val);
}
throw new CastError('number', val, path);
};
+35
View File
@@ -0,0 +1,35 @@
'use strict';
const CastError = require('../error/cast');
/*!
* Given a value, cast it to a string, or throw a `CastError` if the value
* cannot be casted. `null` and `undefined` are considered valid.
*
* @param {Any} value
* @param {String} [path] optional the path to set on the CastError
* @return {string|null|undefined}
* @throws {CastError}
* @api private
*/
module.exports = function castString(value, path) {
// If null or undefined
if (value == null) {
return value;
}
// handle documents being passed
if (value._id && typeof value._id === 'string') {
return value._id;
}
// Re: gh-647 and gh-3030, we're ok with casting using `toString()`
// **unless** its the default Object.toString, because "[object Object]"
// doesn't really qualify as useful data
if (value.toString && value.toString !== Object.prototype.toString) {
return value.toString();
}
throw new CastError('string', value, path);
};
+261
View File
@@ -0,0 +1,261 @@
'use strict';
/*!
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter;
const STATES = require('./connectionstate');
const immediate = require('./helpers/immediate');
/**
* Abstract Collection constructor
*
* This is the base class that drivers inherit from and implement.
*
* @param {String} name name of the collection
* @param {Connection} conn A MongooseConnection instance
* @param {Object} opts optional collection options
* @api public
*/
function Collection(name, conn, opts) {
if (opts === void 0) {
opts = {};
}
if (opts.capped === void 0) {
opts.capped = {};
}
opts.bufferCommands = undefined === opts.bufferCommands
? true
: opts.bufferCommands;
if (typeof opts.capped === 'number') {
opts.capped = {size: opts.capped};
}
this.opts = opts;
this.name = name;
this.collectionName = name;
this.conn = conn;
this.queue = [];
this.buffer = this.opts.bufferCommands;
this.emitter = new EventEmitter();
if (STATES.connected === this.conn.readyState) {
this.onOpen();
}
}
/**
* The collection name
*
* @api public
* @property name
*/
Collection.prototype.name;
/**
* The collection name
*
* @api public
* @property collectionName
*/
Collection.prototype.collectionName;
/**
* The Connection instance
*
* @api public
* @property conn
*/
Collection.prototype.conn;
/**
* Called when the database connects
*
* @api private
*/
Collection.prototype.onOpen = function() {
this.buffer = false;
immediate(() => this.doQueue());
};
/**
* Called when the database disconnects
*
* @api private
*/
Collection.prototype.onClose = function(force) {
if (this.opts.bufferCommands && !force) {
this.buffer = true;
}
};
/**
* Queues a method for later execution when its
* database connection opens.
*
* @param {String} name name of the method to queue
* @param {Array} args arguments to pass to the method when executed
* @api private
*/
Collection.prototype.addQueue = function(name, args) {
this.queue.push([name, args]);
return this;
};
/**
* Executes all queued methods and clears the queue.
*
* @api private
*/
Collection.prototype.doQueue = function() {
for (let i = 0, l = this.queue.length; i < l; i++) {
if (typeof this.queue[i][0] === 'function') {
this.queue[i][0].apply(this, this.queue[i][1]);
} else {
this[this.queue[i][0]].apply(this, this.queue[i][1]);
}
}
this.queue = [];
const _this = this;
process.nextTick(function() {
_this.emitter.emit('queue');
});
return this;
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.ensureIndex = function() {
throw new Error('Collection#ensureIndex unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.createIndex = function() {
throw new Error('Collection#ensureIndex unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.findAndModify = function() {
throw new Error('Collection#findAndModify unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.findOneAndUpdate = function() {
throw new Error('Collection#findOneAndUpdate unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.findOneAndDelete = function() {
throw new Error('Collection#findOneAndDelete unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.findOne = function() {
throw new Error('Collection#findOne unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.find = function() {
throw new Error('Collection#find unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.insert = function() {
throw new Error('Collection#insert unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.insertOne = function() {
throw new Error('Collection#insertOne unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.insertMany = function() {
throw new Error('Collection#insertMany unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.save = function() {
throw new Error('Collection#save unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.update = function() {
throw new Error('Collection#update unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.getIndexes = function() {
throw new Error('Collection#getIndexes unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.mapReduce = function() {
throw new Error('Collection#mapReduce unimplemented by driver');
};
/**
* Abstract method that drivers must implement.
*/
Collection.prototype.watch = function() {
throw new Error('Collection#watch unimplemented by driver');
};
/*!
* Module exports.
*/
module.exports = Collection;
+883
View File
@@ -0,0 +1,883 @@
'use strict';
/*!
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter;
const Schema = require('./schema');
const Collection = require('./driver').get().Collection;
const STATES = require('./connectionstate');
const MongooseError = require('./error');
const PromiseProvider = require('./promise_provider');
const get = require('lodash.get');
const mongodb = require('mongodb');
const utils = require('./utils');
const parseConnectionString = require('mongodb-core').parseConnectionString;
/*!
* A list of authentication mechanisms that don't require a password for authentication.
* This is used by the authMechanismDoesNotRequirePassword method.
*
* @api private
*/
const noPasswordAuthMechanisms = [
'MONGODB-X509'
];
/**
* Connection constructor
*
* For practical reasons, a Connection equals a Db.
*
* @param {Mongoose} base a mongoose instance
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `connecting`: Emitted when `connection.openUri()` is executed on this connection.
* @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
* @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.
* @event `disconnecting`: Emitted when `connection.close()` was executed.
* @event `disconnected`: Emitted after getting disconnected from the db.
* @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.
* @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection.
* @event `error`: Emitted when an error occurs on this connection.
* @event `fullsetup`: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
* @event `all`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
* @api public
*/
function Connection(base) {
this.base = base;
this.collections = {};
this.models = {};
this.config = {autoIndex: true};
this.replica = false;
this.options = null;
this.otherDbs = []; // FIXME: To be replaced with relatedDbs
this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection
this.states = STATES;
this._readyState = STATES.disconnected;
this._closeCalled = false;
this._hasOpened = false;
}
/*!
* Inherit from EventEmitter
*/
Connection.prototype.__proto__ = EventEmitter.prototype;
/**
* Connection ready state
*
* - 0 = disconnected
* - 1 = connected
* - 2 = connecting
* - 3 = disconnecting
*
* Each state change emits its associated event name.
*
* ####Example
*
* conn.on('connected', callback);
* conn.on('disconnected', callback);
*
* @property readyState
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'readyState', {
get: function() {
return this._readyState;
},
set: function(val) {
if (!(val in STATES)) {
throw new Error('Invalid connection state: ' + val);
}
if (this._readyState !== val) {
this._readyState = val;
// [legacy] loop over the otherDbs on this connection and change their state
for (let i = 0; i < this.otherDbs.length; i++) {
this.otherDbs[i].readyState = val;
}
// loop over relatedDbs on this connection and change their state
for (const k in this.relatedDbs) {
this.relatedDbs[k].readyState = val;
}
if (STATES.connected === val) {
this._hasOpened = true;
}
this.emit(STATES[val]);
}
}
});
/**
* A hash of the collections associated with this connection
*
* @property collections
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.collections;
/**
* The name of the database this connection points to.
*
* ####Example
*
* mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb"
*
* @property name
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.name;
/**
* The host name portion of the URI. If multiple hosts, such as a replica set,
* this will contain the first host name in the URI
*
* ####Example
*
* mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost"
*
* @property host
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'host', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The port portion of the URI. If multiple hosts, such as a replica set,
* this will contain the port from the first host name in the URI.
*
* ####Example
*
* mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017
*
* @property port
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'port', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The username specified in the URI
*
* ####Example
*
* mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val"
*
* @property user
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'user', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The password specified in the URI
*
* ####Example
*
* mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw"
*
* @property pass
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'pass', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The mongodb.Db instance, set when the connection is opened
*
* @property db
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.db;
/**
* A hash of the global options that are associated with this connection
*
* @property config
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.config;
/**
* Helper for `createCollection()`. Will explicitly create the given collection
* with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
* and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
*
* Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection)
*
* @method createCollection
* @param {string} collection The collection to create
* @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection)
* @param {Function} [callback]
* @return {Promise}
* @api public
*/
Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
this.db.createCollection(collection, options, cb);
});
/**
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
* and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
*
* ####Example:
*
* const session = await conn.startSession();
* let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
* await doc.remove();
* // `doc` will always be null, even if reading from a replica set
* // secondary. Without causal consistency, it is possible to
* // get a doc back from the below query if the query reads from a
* // secondary that is experiencing replication lag.
* doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
*
*
* @method startSession
* @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
* @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
* @param {Function} [callback]
* @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
* @api public
*/
Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) {
if (typeof options === 'function') {
cb = options;
options = null;
}
const session = this.client.startSession(options);
cb(null, session);
});
/**
* Helper for `dropCollection()`. Will delete the given collection, including
* all documents and indexes.
*
* @method dropCollection
* @param {string} collection The collection to delete
* @param {Function} [callback]
* @return {Promise}
* @api public
*/
Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) {
this.db.dropCollection(collection, cb);
});
/**
* Helper for `dropDatabase()`. Deletes the given database, including all
* collections, documents, and indexes.
*
* @method dropDatabase
* @param {Function} [callback]
* @return {Promise}
* @api public
*/
Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
this.db.dropDatabase(cb);
});
/*!
* ignore
*/
function _wrapConnHelper(fn) {
return function() {
const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null;
const argsWithoutCb = typeof cb === 'function' ?
Array.prototype.slice.call(arguments, 0, arguments.length - 1) :
Array.prototype.slice.call(arguments);
return utils.promiseOrCallback(cb, cb => {
if (this.readyState !== STATES.connected) {
this.once('open', function() {
fn.apply(this, argsWithoutCb.concat([cb]));
});
} else {
fn.apply(this, argsWithoutCb.concat([cb]));
}
});
};
}
/**
* error
*
* Graceful error handling, passes error to callback
* if available, else emits error on the connection.
*
* @param {Error} err
* @param {Function} callback optional
* @api private
*/
Connection.prototype.error = function(err, callback) {
if (callback) {
callback(err);
return null;
}
if (this.listeners('error').length > 0) {
this.emit('error', err);
}
return Promise.reject(err);
};
/**
* Called when the connection is opened
*
* @api private
*/
Connection.prototype.onOpen = function() {
this.readyState = STATES.connected;
// avoid having the collection subscribe to our event emitter
// to prevent 0.3 warning
for (const i in this.collections) {
if (utils.object.hasOwnProperty(this.collections, i)) {
this.collections[i].onOpen();
}
}
this.emit('open');
};
/**
* Opens the connection with a URI using `MongoClient.connect()`.
*
* @param {String} uri The URI to connect with.
* @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect
* @param {Function} [callback]
* @returns {Connection} this
* @api private
*/
Connection.prototype.openUri = function(uri, options, callback) {
this.readyState = STATES.connecting;
this._closeCalled = false;
if (typeof options === 'function') {
callback = options;
options = null;
}
if (['string', 'number'].indexOf(typeof options) !== -1) {
throw new MongooseError('Mongoose 5.x no longer supports ' +
'`mongoose.connect(host, dbname, port)` or ' +
'`mongoose.createConnection(host, dbname, port)`. See ' +
'http://mongoosejs.com/docs/connections.html for supported connection syntax');
}
if (typeof uri !== 'string') {
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
`string, got "${typeof uri}". Make sure the first parameter to ` +
'`mongoose.connect()` or `mongoose.createConnection()` is a string.');
}
const Promise = PromiseProvider.get();
const _this = this;
if (options) {
options = utils.clone(options);
const autoIndex = options.config && options.config.autoIndex != null ?
options.config.autoIndex :
options.autoIndex;
if (autoIndex != null) {
this.config.autoIndex = autoIndex !== false;
delete options.config;
delete options.autoIndex;
}
// Backwards compat
if (options.user || options.pass) {
options.auth = options.auth || {};
options.auth.user = options.user;
options.auth.password = options.pass;
this.user = options.user;
this.pass = options.pass;
}
delete options.user;
delete options.pass;
if (options.bufferCommands != null) {
options.bufferMaxEntries = 0;
this.config.bufferCommands = options.bufferCommands;
delete options.bufferCommands;
}
if (options.useMongoClient != null) {
handleUseMongoClient(options);
}
} else {
options = {};
}
this._connectionOptions = options;
const dbName = options.dbName;
if (dbName != null) {
this.$dbName = dbName;
}
delete options.dbName;
if (!('promiseLibrary' in options)) {
options.promiseLibrary = PromiseProvider.get();
}
if (!('useNewUrlParser' in options)) {
if ('useNewUrlParser' in this.base.options) {
options.useNewUrlParser = this.base.options.useNewUrlParser;
} else {
options.useNewUrlParser = false;
}
}
const parsePromise = new Promise((resolve, reject) => {
parseConnectionString(uri, options, (err, parsed) => {
if (err) {
return reject(err);
}
this.name = dbName != null ? dbName : get(parsed, 'auth.db', null);
this.host = get(parsed, 'hosts.0.host') || 'localhost';
this.port = get(parsed, 'hosts.0.port') || 27017;
this.user = this.user || get(parsed, 'auth.username');
this.pass = this.pass || get(parsed, 'auth.password');
resolve();
});
});
const promise = new Promise((resolve, reject) => {
const client = new mongodb.MongoClient(uri, options);
_this.client = client;
client.connect(function(error) {
if (error) {
_this.readyState = STATES.disconnected;
return reject(error);
}
const db = dbName != null ? client.db(dbName) : client.db();
_this.db = db;
// Backwards compat for mongoose 4.x
db.on('reconnect', function() {
_this.readyState = STATES.connected;
_this.emit('reconnect');
_this.emit('reconnected');
});
db.s.topology.on('reconnectFailed', function() {
_this.emit('reconnectFailed');
});
db.s.topology.on('left', function(data) {
_this.emit('left', data);
});
db.s.topology.on('joined', function(data) {
_this.emit('joined', data);
});
db.s.topology.on('fullsetup', function(data) {
_this.emit('fullsetup', data);
});
db.on('close', function() {
// Implicitly emits 'disconnected'
_this.readyState = STATES.disconnected;
});
db.on('timeout', function() {
_this.emit('timeout');
});
delete _this.then;
delete _this.catch;
_this.readyState = STATES.connected;
for (const i in _this.collections) {
if (utils.object.hasOwnProperty(_this.collections, i)) {
_this.collections[i].onOpen();
}
}
resolve(_this);
_this.emit('open');
});
});
this.$initialConnection = Promise.all([promise, parsePromise]).
then(res => res[0]).
catch(err => {
if (this.listeners('error').length > 0) {
process.nextTick(() => this.emit('error', err));
return;
}
throw err;
});
this.then = function(resolve, reject) {
return this.$initialConnection.then(resolve, reject);
};
this.catch = function(reject) {
return this.$initialConnection.catch(reject);
};
if (callback != null) {
this.$initialConnection.then(
() => callback(null, this),
err => callback(err)
);
}
return this;
};
/*!
* ignore
*/
const handleUseMongoClient = function handleUseMongoClient(options) {
console.warn('WARNING: The `useMongoClient` option is no longer ' +
'necessary in mongoose 5.x, please remove it.');
const stack = new Error().stack;
console.warn(stack.substr(stack.indexOf('\n') + 1));
delete options.useMongoClient;
};
/**
* Closes the connection
*
* @param {Boolean} [force] optional
* @param {Function} [callback] optional
* @return {Connection} self
* @api public
*/
Connection.prototype.close = function(force, callback) {
if (typeof force === 'function') {
callback = force;
force = false;
}
this.$wasForceClosed = !!force;
return utils.promiseOrCallback(callback, cb => {
this._close(force, cb);
});
};
/**
* Handles closing the connection
*
* @param {Boolean} force
* @param {Function} callback
* @api private
*/
Connection.prototype._close = function(force, callback) {
const _this = this;
this._closeCalled = true;
switch (this.readyState) {
case 0: // disconnected
callback();
break;
case 1: // connected
this.readyState = STATES.disconnecting;
this.doClose(force, function(err) {
if (err) {
return callback(err);
}
_this.onClose(force);
callback(null);
});
break;
case 2: // connecting
this.once('open', function() {
_this.close(callback);
});
break;
case 3: // disconnecting
this.once('close', function() {
callback();
});
break;
}
return this;
};
/**
* Called when the connection closes
*
* @api private
*/
Connection.prototype.onClose = function(force) {
this.readyState = STATES.disconnected;
// avoid having the collection subscribe to our event emitter
// to prevent 0.3 warning
for (const i in this.collections) {
if (utils.object.hasOwnProperty(this.collections, i)) {
this.collections[i].onClose(force);
}
}
this.emit('close', force);
};
/**
* Retrieves a collection, creating it if not cached.
*
* Not typically needed by applications. Just talk to your collection through your model.
*
* @param {String} name of the collection
* @param {Object} [options] optional collection options
* @return {Collection} collection instance
* @api public
*/
Connection.prototype.collection = function(name, options) {
options = options ? utils.clone(options) : {};
options.$wasForceClosed = this.$wasForceClosed;
if (!(name in this.collections)) {
this.collections[name] = new Collection(name, this, options);
}
return this.collections[name];
};
/**
* Defines or retrieves a model.
*
* var mongoose = require('mongoose');
* var db = mongoose.createConnection(..);
* db.model('Venue', new Schema(..));
* var Ticket = db.model('Ticket', new Schema(..));
* var Venue = db.model('Venue');
*
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
*
* ####Example:
*
* var schema = new Schema({ name: String }, { collection: 'actor' });
*
* // or
*
* schema.set('collection', 'actor');
*
* // or
*
* var collectionName = 'actor'
* var M = conn.model('Actor', schema, collectionName)
*
* @param {String|Function} name the model name or class extending Model
* @param {Schema} [schema] a schema. necessary when defining a model
* @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
* @see Mongoose#model #index_Mongoose-model
* @return {Model} The compiled model
* @api public
*/
Connection.prototype.model = function(name, schema, collection) {
if (!(this instanceof Connection)) {
throw new MongooseError('`connection.model()` should not be run with ' +
'`new`. If you are doing `new db.model(foo)(bar)`, use ' +
'`db.model(foo)(bar)` instead');
}
let fn;
if (typeof name === 'function') {
fn = name;
name = fn.name;
}
// collection name discovery
if (typeof schema === 'string') {
collection = schema;
schema = false;
}
if (utils.isObject(schema) && !schema.instanceOfSchema) {
schema = new Schema(schema);
}
if (schema && !schema.instanceOfSchema) {
throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
'schema or a POJO');
}
if (this.models[name] && !collection) {
// model exists but we are not subclassing with custom collection
if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
throw new MongooseError.OverwriteModelError(name);
}
return this.models[name];
}
const opts = {cache: false, connection: this};
let model;
if (schema && schema.instanceOfSchema) {
// compile a model
model = this.base.model(fn || name, schema, collection, opts);
// only the first model with this name is cached to allow
// for one-offs with custom collection names etc.
if (!this.models[name]) {
this.models[name] = model;
}
// Errors handled internally, so safe to ignore error
model.init(function $modelInitNoop() {});
return model;
}
if (this.models[name] && collection) {
// subclassing current model with alternate collection
model = this.models[name];
schema = model.prototype.schema;
const sub = model.__subclass(this, schema, collection);
// do not cache the sub model
return sub;
}
// lookup model in mongoose module
model = this.base.models[name];
if (!model) {
throw new MongooseError.MissingSchemaError(name);
}
if (this === model.prototype.db
&& (!collection || collection === model.collection.name)) {
// model already uses this connection.
// only the first model with this name is cached to allow
// for one-offs with custom collection names etc.
if (!this.models[name]) {
this.models[name] = model;
}
return model;
}
this.models[name] = model.__subclass(this, schema, collection);
return this.models[name];
};
/**
* Returns an array of model names created on this connection.
* @api public
* @return {Array}
*/
Connection.prototype.modelNames = function() {
return Object.keys(this.models);
};
/**
* @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());
};
/**
* @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 openUri 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 noPasswordAuthMechanisms.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 openUri 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());
};
/**
* Switches to a different database using the same connection pool.
*
* Returns a new connection object, with the new db.
*
* @method useDb
* @memberOf Connection
* @param {String} name The database name
* @return {Connection} New Connection Object
* @api public
*/
/*!
* Module exports.
*/
Connection.STATES = STATES;
module.exports = Connection;
+26
View File
@@ -0,0 +1,26 @@
/*!
* Connection states
*/
'use strict';
const STATES = module.exports = exports = Object.create(null);
const disconnected = 'disconnected';
const connected = 'connected';
const connecting = 'connecting';
const disconnecting = 'disconnecting';
const uninitialized = 'uninitialized';
STATES[0] = disconnected;
STATES[1] = connected;
STATES[2] = connecting;
STATES[3] = disconnecting;
STATES[99] = uninitialized;
STATES[disconnected] = 0;
STATES[connected] = 1;
STATES[connecting] = 2;
STATES[disconnecting] = 3;
STATES[uninitialized] = 99;
+283
View File
@@ -0,0 +1,283 @@
/*!
* Module dependencies.
*/
'use strict';
const Readable = require('stream').Readable;
const eachAsync = require('../helpers/cursor/eachAsync');
const util = require('util');
const utils = require('../utils');
/**
* An AggregationCursor is a concurrency primitive for processing aggregation
* results one document at a time. It is analogous to QueryCursor.
*
* An AggregationCursor fulfills the Node.js streams3 API,
* in addition to several other mechanisms for loading documents from MongoDB
* one at a time.
*
* Creating an AggregationCursor executes the model's pre aggregate hooks,
* but **not** the model's post aggregate hooks.
*
* Unless you're an advanced user, do **not** instantiate this class directly.
* Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead.
*
* @param {Aggregate} agg
* @param {Object} options
* @inherits Readable
* @event `cursor`: Emitted when the cursor is created
* @event `error`: Emitted when an error occurred
* @event `data`: Emitted when the stream is flowing and the next doc is ready
* @event `end`: Emitted when the stream is exhausted
* @api public
*/
function AggregationCursor(agg) {
Readable.call(this, { objectMode: true });
this.cursor = null;
this.agg = agg;
this._transforms = [];
const model = agg._model;
delete agg.options.cursor.useMongooseAggCursor;
_init(model, this, agg);
}
util.inherits(AggregationCursor, Readable);
/*!
* ignore
*/
function _init(model, c, agg) {
if (!model.collection.buffer) {
model.hooks.execPre('aggregate', agg, function() {
c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
c.emit('cursor', c.cursor);
});
} else {
model.collection.emitter.once('queue', function() {
model.hooks.execPre('aggregate', agg, function() {
c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
c.emit('cursor', c.cursor);
});
});
}
}
/*!
* Necessary to satisfy the Readable API
*/
AggregationCursor.prototype._read = function() {
const _this = this;
_next(this, function(error, doc) {
if (error) {
return _this.emit('error', error);
}
if (!doc) {
_this.push(null);
_this.cursor.close(function(error) {
if (error) {
return _this.emit('error', error);
}
setTimeout(function() {
_this.emit('close');
}, 0);
});
return;
}
_this.push(doc);
});
};
/**
* Registers a transform function which subsequently maps documents retrieved
* via the streams interface or `.next()`
*
* ####Example
*
* // Map documents returned by `data` events
* Thing.
* find({ name: /^hello/ }).
* cursor().
* map(function (doc) {
* doc.foo = "bar";
* return doc;
* })
* on('data', function(doc) { console.log(doc.foo); });
*
* // Or map documents returned by `.next()`
* var cursor = Thing.find({ name: /^hello/ }).
* cursor().
* map(function (doc) {
* doc.foo = "bar";
* return doc;
* });
* cursor.next(function(error, doc) {
* console.log(doc.foo);
* });
*
* @param {Function} fn
* @return {QueryCursor}
* @api public
* @method map
*/
AggregationCursor.prototype.map = function(fn) {
this._transforms.push(fn);
return this;
};
/*!
* Marks this cursor as errored
*/
AggregationCursor.prototype._markError = function(error) {
this._error = error;
return this;
};
/**
* Marks this cursor as closed. Will stop streaming and subsequent calls to
* `next()` will error.
*
* @param {Function} callback
* @return {Promise}
* @api public
* @method close
* @emits close
* @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
*/
AggregationCursor.prototype.close = function(callback) {
return utils.promiseOrCallback(callback, cb => {
this.cursor.close(error => {
if (error) {
cb(error);
return this.listeners('error').length > 0 && this.emit('error', error);
}
this.emit('close');
cb(null);
});
});
};
/**
* Get the next document from this cursor. Will return `null` when there are
* no documents left.
*
* @param {Function} callback
* @return {Promise}
* @api public
* @method next
*/
AggregationCursor.prototype.next = function(callback) {
return utils.promiseOrCallback(callback, cb => {
_next(this, cb);
});
};
/**
* Execute `fn` for every document in the cursor. If `fn` returns a promise,
* will wait for the promise to resolve before iterating on to the next one.
* Returns a promise that resolves when done.
*
* @param {Function} fn
* @param {Object} [options]
* @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1.
* @param {Function} [callback] executed when all docs have been processed
* @return {Promise}
* @api public
* @method eachAsync
*/
AggregationCursor.prototype.eachAsync = function(fn, opts, callback) {
const _this = this;
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback);
};
/**
* Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
* Useful for setting the `noCursorTimeout` and `tailable` flags.
*
* @param {String} flag
* @param {Boolean} value
* @return {AggregationCursor} this
* @api public
* @method addCursorFlag
*/
AggregationCursor.prototype.addCursorFlag = function(flag, value) {
const _this = this;
_waitForCursor(this, function() {
_this.cursor.addCursorFlag(flag, value);
});
return this;
};
/*!
* ignore
*/
function _waitForCursor(ctx, cb) {
if (ctx.cursor) {
return cb();
}
ctx.once('cursor', function() {
cb();
});
}
/*!
* Get the next doc from the underlying cursor and mongooseify it
* (populate, etc.)
*/
function _next(ctx, cb) {
let callback = cb;
if (ctx._transforms.length) {
callback = function(err, doc) {
if (err || doc === null) {
return cb(err, doc);
}
cb(err, ctx._transforms.reduce(function(doc, fn) {
return fn(doc);
}, doc));
};
}
if (ctx._error) {
return process.nextTick(function() {
callback(ctx._error);
});
}
if (ctx.cursor) {
return ctx.cursor.next(function(error, doc) {
if (error) {
return callback(error);
}
if (!doc) {
return callback(null, null);
}
callback(null, doc);
});
} else {
ctx.once('cursor', function() {
_next(ctx, cb);
});
}
}
module.exports = AggregationCursor;
+48
View File
@@ -0,0 +1,48 @@
'use strict';
/*!
* Module dependencies.
*/
const EventEmitter = require('events').EventEmitter;
/*!
* ignore
*/
class ChangeStream extends EventEmitter {
constructor(model, pipeline, options) {
super();
this.driverChangeStream = null;
// This wrapper is necessary because of buffering.
if (model.collection.buffer) {
model.collection.addQueue(() => {
this.driverChangeStream = model.collection.watch(pipeline, options);
this._bindEvents();
this.emit('ready');
});
} else {
this.driverChangeStream = model.collection.watch(pipeline, options);
this._bindEvents();
this.emit('ready');
}
}
_bindEvents() {
['close', 'change', 'end', 'error'].forEach(ev => {
this.driverChangeStream.on(ev, data => this.emit(ev, data));
});
}
_queue(cb) {
this.once('ready', () => cb());
}
}
/*!
* ignore
*/
module.exports = ChangeStream;
+313
View File
@@ -0,0 +1,313 @@
/*!
* Module dependencies.
*/
'use strict';
const Readable = require('stream').Readable;
const eachAsync = require('../helpers/cursor/eachAsync');
const helpers = require('../queryhelpers');
const util = require('util');
const utils = require('../utils');
/**
* A QueryCursor is a concurrency primitive for processing query results
* one document at a time. A QueryCursor fulfills the Node.js streams3 API,
* in addition to several other mechanisms for loading documents from MongoDB
* one at a time.
*
* QueryCursors execute the model's pre find hooks, but **not** the model's
* post find hooks.
*
* Unless you're an advanced user, do **not** instantiate this class directly.
* Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead.
*
* @param {Query} query
* @param {Object} options query options passed to `.find()`
* @inherits Readable
* @event `cursor`: Emitted when the cursor is created
* @event `error`: Emitted when an error occurred
* @event `data`: Emitted when the stream is flowing and the next doc is ready
* @event `end`: Emitted when the stream is exhausted
* @api public
*/
function QueryCursor(query, options) {
Readable.call(this, { objectMode: true });
this.cursor = null;
this.query = query;
this._transforms = options.transform ? [options.transform] : [];
const _this = this;
const model = query.model;
model.hooks.execPre('find', query, function() {
model.collection.find(query._conditions, options, function(err, cursor) {
if (_this._error) {
cursor.close(function() {});
_this.listeners('error').length > 0 && _this.emit('error', _this._error);
}
if (err) {
return _this.emit('error', err);
}
_this.cursor = cursor;
_this.emit('cursor', cursor);
});
});
}
util.inherits(QueryCursor, Readable);
/*!
* Necessary to satisfy the Readable API
*/
QueryCursor.prototype._read = function() {
const _this = this;
_next(this, function(error, doc) {
if (error) {
return _this.emit('error', error);
}
if (!doc) {
_this.push(null);
_this.cursor.close(function(error) {
if (error) {
return _this.emit('error', error);
}
setTimeout(function() {
_this.emit('close');
}, 0);
});
return;
}
_this.push(doc);
});
};
/**
* Registers a transform function which subsequently maps documents retrieved
* via the streams interface or `.next()`
*
* ####Example
*
* // Map documents returned by `data` events
* Thing.
* find({ name: /^hello/ }).
* cursor().
* map(function (doc) {
* doc.foo = "bar";
* return doc;
* })
* on('data', function(doc) { console.log(doc.foo); });
*
* // Or map documents returned by `.next()`
* var cursor = Thing.find({ name: /^hello/ }).
* cursor().
* map(function (doc) {
* doc.foo = "bar";
* return doc;
* });
* cursor.next(function(error, doc) {
* console.log(doc.foo);
* });
*
* @param {Function} fn
* @return {QueryCursor}
* @api public
* @method map
*/
QueryCursor.prototype.map = function(fn) {
this._transforms.push(fn);
return this;
};
/*!
* Marks this cursor as errored
*/
QueryCursor.prototype._markError = function(error) {
this._error = error;
return this;
};
/**
* Marks this cursor as closed. Will stop streaming and subsequent calls to
* `next()` will error.
*
* @param {Function} callback
* @return {Promise}
* @api public
* @method close
* @emits close
* @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
*/
QueryCursor.prototype.close = function(callback) {
return utils.promiseOrCallback(callback, cb => {
this.cursor.close(error => {
if (error) {
cb(error);
return this.listeners('error').length > 0 && this.emit('error', error);
}
this.emit('close');
cb(null);
});
});
};
/**
* Get the next document from this cursor. Will return `null` when there are
* no documents left.
*
* @param {Function} callback
* @return {Promise}
* @api public
* @method next
*/
QueryCursor.prototype.next = function(callback) {
return utils.promiseOrCallback(callback, cb => {
_next(this, function(error, doc) {
if (error) {
return cb(error);
}
cb(null, doc);
});
});
};
/**
* Execute `fn` for every document in the cursor. If `fn` returns a promise,
* will wait for the promise to resolve before iterating on to the next one.
* Returns a promise that resolves when done.
*
* @param {Function} fn
* @param {Object} [options]
* @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1.
* @param {Function} [callback] executed when all docs have been processed
* @return {Promise}
* @api public
* @method eachAsync
*/
QueryCursor.prototype.eachAsync = function(fn, opts, callback) {
const _this = this;
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback);
};
/**
* Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
* Useful for setting the `noCursorTimeout` and `tailable` flags.
*
* @param {String} flag
* @param {Boolean} value
* @return {AggregationCursor} this
* @api public
* @method addCursorFlag
*/
QueryCursor.prototype.addCursorFlag = function(flag, value) {
const _this = this;
_waitForCursor(this, function() {
_this.cursor.addCursorFlag(flag, value);
});
return this;
};
/*!
* Get the next doc from the underlying cursor and mongooseify it
* (populate, etc.)
*/
function _next(ctx, cb) {
let callback = cb;
if (ctx._transforms.length) {
callback = function(err, doc) {
if (err || doc === null) {
return cb(err, doc);
}
cb(err, ctx._transforms.reduce(function(doc, fn) {
return fn(doc);
}, doc));
};
}
if (ctx._error) {
return process.nextTick(function() {
callback(ctx._error);
});
}
if (ctx.cursor) {
return ctx.cursor.next(function(error, doc) {
if (error) {
return callback(error);
}
if (!doc) {
return callback(null, null);
}
const opts = ctx.query._mongooseOptions;
if (!opts.populate) {
return opts.lean === true ?
callback(null, doc) :
_create(ctx, doc, null, callback);
}
const pop = helpers.preparePopulationOptionsMQ(ctx.query,
ctx.query._mongooseOptions);
pop.__noPromise = true;
ctx.query.model.populate(doc, pop, function(err, doc) {
if (err) {
return callback(err);
}
return opts.lean === true ?
callback(null, doc) :
_create(ctx, doc, pop, callback);
});
});
} else {
ctx.once('cursor', function() {
_next(ctx, cb);
});
}
}
/*!
* ignore
*/
function _waitForCursor(ctx, cb) {
if (ctx.cursor) {
return cb();
}
ctx.once('cursor', function() {
cb();
});
}
/*!
* Convert a raw doc into a full mongoose doc.
*/
function _create(ctx, doc, populatedIds, cb) {
const instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields);
const opts = populatedIds ?
{ populated: populatedIds } :
undefined;
instance.init(doc, opts, function(err) {
if (err) {
return cb(err);
}
cb(null, instance);
});
}
module.exports = QueryCursor;
+2990
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
'use strict';
/* eslint-env browser */
/*!
* Module dependencies.
*/
const Document = require('./document.js');
const BrowserDocument = require('./browserDocument.js');
let isBrowser = false;
/**
* Returns the Document constructor for the current context
*
* @api private
*/
module.exports = function() {
if (isBrowser) {
return BrowserDocument;
}
return Document;
};
/*!
* ignore
*/
module.exports.setBrowser = function(flag) {
isBrowser = flag;
};
+15
View File
@@ -0,0 +1,15 @@
'use strict';
/*!
* ignore
*/
let driver = null;
module.exports.get = function() {
return driver;
};
module.exports.set = function(v) {
driver = v;
};
+4
View File
@@ -0,0 +1,4 @@
# Driver Spec
TODO
+7
View File
@@ -0,0 +1,7 @@
/*!
* ignore
*/
'use strict';
module.exports = function() {};
+14
View File
@@ -0,0 +1,14 @@
/*!
* Module dependencies.
*/
'use strict';
const Binary = require('bson').Binary;
/*!
* Module exports.
*/
module.exports = exports = Binary;
+7
View File
@@ -0,0 +1,7 @@
/*!
* ignore
*/
'use strict';
module.exports = require('bson').Decimal128;
+13
View File
@@ -0,0 +1,13 @@
/*!
* Module exports.
*/
'use strict';
exports.Binary = require('./binary');
exports.Collection = function() {
throw new Error('Cannot create a collection from browser library');
};
exports.Decimal128 = require('./decimal128');
exports.ObjectId = require('./objectid');
exports.ReadPreference = require('./ReadPreference');
+28
View File
@@ -0,0 +1,28 @@
/*!
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
* @constructor NodeMongoDbObjectId
* @see ObjectId
*/
'use strict';
const ObjectId = require('bson').ObjectID;
/*!
* Getter for convenience with populate, see gh-6115
*/
Object.defineProperty(ObjectId.prototype, '_id', {
enumerable: false,
configurable: true,
get: function() {
return this;
}
});
/*!
* ignore
*/
module.exports = exports = ObjectId;
@@ -0,0 +1,47 @@
/*!
* Module dependencies.
*/
'use strict';
const mongodb = require('mongodb');
const 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);
};
+10
View File
@@ -0,0 +1,10 @@
/*!
* Module dependencies.
*/
'use strict';
const Binary = require('mongodb').Binary;
module.exports = exports = Binary;
@@ -0,0 +1,309 @@
'use strict';
/*!
* Module dependencies.
*/
const MongooseCollection = require('../../collection');
const Collection = require('mongodb').Collection;
const get = require('lodash.get');
const sliced = require('sliced');
const util = require('util');
/**
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation.
*
* All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management.
*
* @inherits Collection
* @api private
*/
function NativeCollection() {
this.collection = null;
MongooseCollection.apply(this, arguments);
}
/*!
* Inherit from abstract Collection.
*/
NativeCollection.prototype.__proto__ = MongooseCollection.prototype;
/**
* Called when the connection opens.
*
* @api private
*/
NativeCollection.prototype.onOpen = function() {
const _this = this;
// always get a new collection in case the user changed host:port
// of parent db instance when re-opening the connection.
if (!_this.opts.capped.size) {
// non-capped
callback(null, _this.conn.db.collection(_this.name));
return _this.collection;
}
// capped
return _this.conn.db.collection(_this.name, function(err, c) {
if (err) return callback(err);
// discover if this collection exists and if it is capped
_this.conn.db.listCollections({name: _this.name}).toArray(function(err, docs) {
if (err) {
return callback(err);
}
const doc = docs[0];
const exists = !!doc;
if (exists) {
if (doc.options && doc.options.capped) {
callback(null, c);
} else {
const msg = 'A non-capped collection exists with the name: ' + _this.name + '\n\n'
+ ' To use this collection as a capped collection, please '
+ 'first convert it.\n'
+ ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped';
err = new Error(msg);
callback(err);
}
} else {
// create
const opts = Object.assign({}, _this.opts.capped);
opts.capped = true;
_this.conn.db.createCollection(_this.name, opts, callback);
}
});
});
function callback(err, collection) {
if (err) {
// likely a strict mode error
_this.conn.emit('error', err);
} else {
_this.collection = collection;
MongooseCollection.prototype.onOpen.call(_this);
}
}
};
/**
* Called when the connection closes
*
* @api private
*/
NativeCollection.prototype.onClose = function(force) {
MongooseCollection.prototype.onClose.call(this, force);
};
/*!
* ignore
*/
const syncCollectionMethods = { watch: true };
/*!
* Copy the collection methods and make them subject to queues
*/
function iter(i) {
NativeCollection.prototype[i] = function() {
const collection = this.collection;
const args = arguments;
const _this = this;
const debug = _this.conn.base.options.debug;
// If user force closed, queueing will hang forever. See #5664
if (this.opts.$wasForceClosed) {
return this.conn.db.collection(this.name)[i].apply(collection, args);
}
if (this.buffer) {
if (syncCollectionMethods[i]) {
throw new Error('Collection method ' + i + ' is synchronous');
}
this.addQueue(i, arguments);
return;
}
if (debug) {
if (typeof debug === 'function') {
debug.apply(_this,
[_this.name, i].concat(sliced(args, 0, args.length - 1)));
} else {
this.$print(_this.name, i, args);
}
}
try {
return collection[i].apply(collection, args);
} catch (error) {
// Collection operation may throw because of max bson size, catch it here
// See gh-3906
if (args.length > 0 &&
typeof args[args.length - 1] === 'function') {
args[args.length - 1](error);
} else {
throw error;
}
}
};
}
for (const 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;
}
iter(i);
}
/**
* Debug print helper
*
* @api public
* @method $print
*/
NativeCollection.prototype.$print = function(name, i, args) {
const moduleName = '\x1B[0;36mMongoose:\x1B[0m ';
const functionCall = [name, i].join('.');
const _args = [];
for (let j = args.length - 1; j >= 0; --j) {
if (this.$format(args[j]) || _args.length) {
_args.unshift(this.$format(args[j]));
}
}
const params = '(' + _args.join(', ') + ')';
console.info(moduleName + functionCall + params);
};
/**
* Formatter for debug print args
*
* @api public
* @method $format
*/
NativeCollection.prototype.$format = function(arg) {
const type = typeof arg;
if (type === 'function' || type === 'undefined') return '';
return format(arg);
};
/*!
* Debug print helper
*/
function inspectable(representation) {
const ret = {
inspect: function() { return representation; },
};
if (util.inspect.custom) {
ret[util.inspect.custom] = ret.inspect;
}
return ret;
}
function map(o) {
return format(o, true);
}
function formatObjectId(x, key) {
x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")');
}
function formatDate(x, key) {
x[key] = inspectable('new Date("' + x[key].toUTCString() + '")');
}
function format(obj, sub) {
if (obj && typeof obj.toBSON === 'function') {
obj = obj.toBSON();
}
if (obj == null) {
return obj;
}
let x = require('../../utils').clone(obj, {transform: false});
if (x.constructor.name === 'Binary') {
x = 'BinData(' + x.sub_type + ', "' + x.toString('base64') + '")';
} else if (x.constructor.name === 'ObjectID') {
x = inspectable('ObjectId("' + x.toHexString() + '")');
} else if (x.constructor.name === 'Date') {
x = inspectable('new Date("' + x.toUTCString() + '")');
} else if (x.constructor.name === 'Object') {
const keys = Object.keys(x);
const numKeys = keys.length;
let key;
for (let i = 0; i < numKeys; ++i) {
key = keys[i];
if (x[key]) {
let error;
if (typeof x[key].toBSON === 'function') {
try {
// `session.toBSON()` throws an error. This means we throw errors
// in debug mode when using transactions, see gh-6712. As a
// workaround, catch `toBSON()` errors, try to serialize without
// `toBSON()`, and rethrow if serialization still fails.
x[key] = x[key].toBSON();
} catch (_error) {
error = _error;
}
}
if (x[key].constructor.name === 'Binary') {
x[key] = 'BinData(' + x[key].sub_type + ', "' +
x[key].buffer.toString('base64') + '")';
} else if (x[key].constructor.name === 'Object') {
x[key] = format(x[key], true);
} else if (x[key].constructor.name === 'ObjectID') {
formatObjectId(x, key);
} else if (x[key].constructor.name === 'Date') {
formatDate(x, key);
} else if (x[key].constructor.name === 'ClientSession') {
x[key] = inspectable('ClientSession("' +
get(x[key], 'id.id.buffer', '').toString('hex') + '")');
} else if (Array.isArray(x[key])) {
x[key] = x[key].map(map);
} else if (error != null) {
// If there was an error with `toBSON()` and the object wasn't
// already converted to a string representation, rethrow it.
// Open to better ideas on how to handle this.
throw error;
}
}
}
}
if (sub) {
return x;
}
return util.
inspect(x, false, 10, true).
replace(/\n/g, '').
replace(/\s{2,}/g, ' ');
}
/**
* Retrieves information about this collections indexes.
*
* @param {Function} callback
* @method getIndexes
* @api public
*/
NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation;
/*!
* Module exports.
*/
module.exports = NativeCollection;
@@ -0,0 +1,175 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseConnection = require('../../connection');
const STATES = require('../../connectionstate');
/**
* A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
*
* @inherits Connection
* @api private
*/
function NativeConnection() {
MongooseConnection.apply(this, arguments);
this._listening = false;
}
/**
* Expose the possible connection states.
* @api public
*/
NativeConnection.STATES = STATES;
/*!
* Inherits from Connection.
*/
NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
/**
* 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, options) {
// Return immediately if cached
if (options && options.useCache && this.relatedDbs[name]) {
return this.relatedDbs[name];
}
// we have to manually copy all of the attributes...
const newConn = new this.constructor();
newConn.name = name;
newConn.base = this.base;
newConn.collections = {};
newConn.models = {};
newConn.replica = this.replica;
newConn.name = this.name;
newConn.options = this.options;
newConn._readyState = this._readyState;
newConn._closeCalled = this._closeCalled;
newConn._hasOpened = this._hasOpened;
newConn._listening = false;
newConn.host = this.host;
newConn.port = this.port;
newConn.user = this.user;
newConn.pass = this.pass;
// 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
const _this = this;
newConn.client = _this.client;
if (this.db && this._readyState === STATES.connected) {
wireup();
} else {
this.once('connected', wireup);
}
function wireup() {
newConn.client = _this.client;
newConn.db = _this.client.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);
// push onto the relatedDbs cache, this is used when state changes
if (options && options.useCache) {
this.relatedDbs[newConn.name] = newConn;
newConn.relatedDbs = this.relatedDbs;
}
return newConn;
};
/*!
* Register listeners for important events and bubble appropriately.
*/
function listen(conn) {
if (conn.db._listening) {
return;
}
conn.db._listening = true;
conn.db.on('close', function(force) {
if (conn._closeCalled) return;
// the driver never emits an `open` event. auto_reconnect still
// emits a `close` event but since we never get another
// `open` we can't emit close
if (conn.db.serverConfig.autoReconnect) {
conn.readyState = STATES.disconnected;
conn.emit('close');
return;
}
conn.onClose(force);
});
conn.db.on('error', function(err) {
conn.emit('error', err);
});
conn.db.on('reconnect', function() {
conn.readyState = STATES.connected;
conn.emit('reconnect');
conn.emit('reconnected');
conn.onOpen();
});
conn.db.on('timeout', function(err) {
conn.emit('timeout', err);
});
conn.db.on('open', function(err, db) {
if (STATES.disconnected === conn.readyState && db && db.databaseName) {
conn.readyState = STATES.connected;
conn.emit('reconnect');
conn.emit('reconnected');
}
});
conn.db.on('parseError', function(err) {
conn.emit('parseError', err);
});
}
/**
* Closes the connection
*
* @param {Boolean} [force]
* @param {Function} [fn]
* @return {Connection} this
* @api private
*/
NativeConnection.prototype.doClose = function(force, fn) {
this.client.close(force, fn);
return this;
};
/*!
* Module exports.
*/
module.exports = NativeConnection;
@@ -0,0 +1,7 @@
/*!
* ignore
*/
'use strict';
module.exports = require('mongodb').Decimal128;
+11
View File
@@ -0,0 +1,11 @@
/*!
* Module exports.
*/
'use strict';
exports.Binary = require('./binary');
exports.Collection = require('./collection');
exports.Decimal128 = require('./decimal128');
exports.ObjectId = require('./objectid');
exports.ReadPreference = require('./ReadPreference');
@@ -0,0 +1,16 @@
/*!
* [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId
* @constructor NodeMongoDbObjectId
* @see ObjectId
*/
'use strict';
const ObjectId = require('mongodb').ObjectId;
/*!
* ignore
*/
module.exports = exports = ObjectId;
+38
View File
@@ -0,0 +1,38 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/*!
* MissingSchema Error constructor.
*
* @inherits MongooseError
*/
function MissingSchemaError() {
const msg = 'Schema hasn\'t been registered for document.\n'
+ 'Use mongoose.Document(name, schema)';
MongooseError.call(this, msg);
this.name = 'MissingSchemaError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
}
/*!
* Inherits from MongooseError.
*/
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = MissingSchemaError;
+62
View File
@@ -0,0 +1,62 @@
'use strict';
/*!
* Module dependencies.
*/
const MongooseError = require('./mongooseError');
const util = require('util');
/**
* Casting Error constructor.
*
* @param {String} type
* @param {String} value
* @inherits MongooseError
* @api private
*/
function CastError(type, value, path, reason) {
let stringValue = util.inspect(value);
stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"');
if (stringValue.charAt(0) !== '"') {
stringValue = '"' + stringValue + '"';
}
MongooseError.call(this, 'Cast to ' + type + ' failed for value ' +
stringValue + ' at path "' + path + '"');
this.name = 'CastError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
this.stringValue = stringValue;
this.kind = type;
this.value = value;
this.path = path;
this.reason = reason;
}
/*!
* Inherits from MongooseError.
*/
CastError.prototype = Object.create(MongooseError.prototype);
CastError.prototype.constructor = MongooseError;
/*!
* ignore
*/
CastError.prototype.setModel = function(model) {
this.model = model;
this.message = 'Cast to ' + this.kind + ' failed for value ' +
this.stringValue + ' at path "' + this.path + '"' + ' for model "' +
model.modelName + '"';
};
/*!
* exports
*/
module.exports = CastError;
+42
View File
@@ -0,0 +1,42 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/**
* Casting Error constructor.
*
* @param {String} type
* @param {String} value
* @inherits MongooseError
* @api private
*/
function DisconnectedError(connectionString) {
MongooseError.call(this, 'Ran out of retries trying to reconnect to "' +
connectionString + '". Try setting `server.reconnectTries` and ' +
'`server.reconnectInterval` to something higher.');
this.name = 'DisconnectedError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
}
/*!
* Inherits from MongooseError.
*/
DisconnectedError.prototype = Object.create(MongooseError.prototype);
DisconnectedError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = DisconnectedError;
+48
View File
@@ -0,0 +1,48 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/*!
* DivergentArrayError constructor.
*
* @inherits MongooseError
*/
function DivergentArrayError(paths) {
const msg = 'For your own good, using `document.save()` to update an array '
+ 'which was selected using an $elemMatch projection OR '
+ 'populated using skip, limit, query conditions, or exclusion of '
+ 'the _id field when the operation results in a $pop or $set of '
+ 'the entire array is not supported. The following '
+ 'path(s) would have been modified unsafely:\n'
+ ' ' + paths.join('\n ') + '\n'
+ 'Use Model.update() to update these arrays instead.';
// TODO write up a docs page (FAQ) and link to it
MongooseError.call(this, msg);
this.name = 'DivergentArrayError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
}
/*!
* Inherits from MongooseError.
*/
DivergentArrayError.prototype = Object.create(MongooseError.prototype);
DivergentArrayError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = DivergentArrayError;
+104
View File
@@ -0,0 +1,104 @@
'use strict';
const MongooseError = require('./mongooseError');
/*!
* Module exports.
*/
module.exports = exports = MongooseError;
/**
* The default built-in validator error messages.
*
* @see Error.messages #error_messages_MongooseError-messages
* @api public
*/
MongooseError.messages = require('./messages');
// backward compat
MongooseError.Messages = MongooseError.messages;
/**
* An instance of this error class will be returned when `save()` fails
* because the underlying
* document was not found. The constructor takes one parameter, the
* conditions that mongoose passed to `update()` when trying to update
* the document.
*
* @api public
*/
MongooseError.DocumentNotFoundError = require('./notFound');
/**
* An instance of this error class will be returned when mongoose failed to
* cast a value.
*
* @api public
*/
MongooseError.CastError = require('./cast');
/**
* An instance of this error class will be returned when [validation](/docs/validation.html) failed.
*
* @api public
*/
MongooseError.ValidationError = require('./validation');
/**
* A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances
*
* @api public
*/
MongooseError.ValidatorError = require('./validator');
/**
* An instance of this error class will be returned when you call `save()` after
* the document in the database was changed in a potentially unsafe way. See
* the [`versionKey` option](/docs/guide.html#versionKey) for more information.
*
* @api public
*/
MongooseError.VersionError = require('./version');
/**
* An instance of this error class will be returned when you call `save()` multiple
* times on the same document in parallel. See the [FAQ](/docs/faq.html) for more
* information.
*
* @api public
*/
MongooseError.ParallelSaveError = require('./parallelSave');
/**
* Thrown when a model with the given name was already registered on the connection.
* See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error).
*
* @api public
*/
MongooseError.OverwriteModelError = require('./overwriteModel');
/**
* Thrown when you try to access a model that has not been registered yet
*
* @api public
*/
MongooseError.MissingSchemaError = require('./missingSchema');
/**
* An instance of this error will be returned if you used an array projection
* and then modified the array in an unsafe way.
*
* @api public
*/
MongooseError.DivergentArrayError = require('./divergentArray');
+46
View File
@@ -0,0 +1,46 @@
/**
* 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.
*
* @static messages
* @receiver MongooseError
* @api public
*/
'use strict';
const msg = module.exports = exports = {};
msg.DocumentNotFoundError = null;
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}).';
+39
View File
@@ -0,0 +1,39 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/*!
* MissingSchema Error constructor.
*
* @inherits MongooseError
*/
function MissingSchemaError(name) {
const msg = 'Schema hasn\'t been registered for model "' + name + '".\n'
+ 'Use mongoose.model(name, schema)';
MongooseError.call(this, msg);
this.name = 'MissingSchemaError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
}
/*!
* Inherits from MongooseError.
*/
MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = MissingSchemaError;
+28
View File
@@ -0,0 +1,28 @@
/**
* MongooseError constructor
*
* @param {String} msg Error message
* @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
*/
'use strict';
function MongooseError(msg) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
this.message = msg;
this.name = 'MongooseError';
}
/*!
* Inherits from Error.
*/
MongooseError.prototype = Object.create(Error.prototype);
MongooseError.prototype.constructor = Error;
module.exports = MongooseError;
+50
View File
@@ -0,0 +1,50 @@
'use strict';
/*!
* Module dependencies.
*/
const MongooseError = require('./');
const util = require('util');
/*!
* OverwriteModel Error constructor.
*
* @inherits MongooseError
*/
function DocumentNotFoundError(query) {
let msg;
const messages = MongooseError.messages;
if (messages.DocumentNotFoundError != null) {
msg = typeof messages.DocumentNotFoundError === 'function' ?
messages.DocumentNotFoundError(query) :
messages.DocumentNotFoundError;
} else {
msg = 'No document found for query "' + util.inspect(query) + '"';
}
MongooseError.call(this, msg);
this.name = 'DocumentNotFoundError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
this.query = query;
}
/*!
* Inherits from MongooseError.
*/
DocumentNotFoundError.prototype = Object.create(MongooseError.prototype);
DocumentNotFoundError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = DocumentNotFoundError;
+37
View File
@@ -0,0 +1,37 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/**
* Strict mode error constructor
*
* @param {String} type
* @param {String} value
* @inherits MongooseError
* @api private
*/
function ObjectExpectedError(path, val) {
MongooseError.call(this, 'Tried to set nested object field `' + path +
'` to primitive value `' + val + '` and strict mode is set to throw.');
this.name = 'ObjectExpectedError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
this.path = path;
}
/*!
* Inherits from MongooseError.
*/
ObjectExpectedError.prototype = Object.create(MongooseError.prototype);
ObjectExpectedError.prototype.constructor = MongooseError;
module.exports = ObjectExpectedError;
+38
View File
@@ -0,0 +1,38 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/**
* Constructor for errors that happen when a parameter that's expected to be
* an object isn't an object
*
* @param {Any} value
* @param {String} paramName
* @param {String} fnName
* @inherits MongooseError
* @api private
*/
function ObjectParameterError(value, paramName, fnName) {
MongooseError.call(this, 'Parameter "' + paramName + '" to ' + fnName +
'() must be an object, got ' + value.toString());
this.name = 'ObjectParameterError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
}
/*!
* Inherits from MongooseError.
*/
ObjectParameterError.prototype = Object.create(MongooseError.prototype);
ObjectParameterError.prototype.constructor = MongooseError;
module.exports = ObjectParameterError;
+37
View File
@@ -0,0 +1,37 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/*!
* OverwriteModel Error constructor.
*
* @inherits MongooseError
*/
function OverwriteModelError(name) {
MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.');
this.name = 'OverwriteModelError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
}
/*!
* Inherits from MongooseError.
*/
OverwriteModelError.prototype = Object.create(MongooseError.prototype);
OverwriteModelError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = OverwriteModelError;
+33
View File
@@ -0,0 +1,33 @@
'use strict';
/*!
* Module dependencies.
*/
const MongooseError = require('./');
/**
* ParallelSave Error constructor.
*
* @inherits MongooseError
* @api private
*/
function ParallelSaveError(doc) {
const msg = 'Can\'t save() the same doc multiple times in parallel. Document: ';
MongooseError.call(this, msg + doc.id);
this.name = 'ParallelSaveError';
}
/*!
* Inherits from MongooseError.
*/
ParallelSaveError.prototype = Object.create(MongooseError.prototype);
ParallelSaveError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = ParallelSaveError;
+38
View File
@@ -0,0 +1,38 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/**
* Strict mode error constructor
*
* @param {String} type
* @param {String} value
* @inherits MongooseError
* @api private
*/
function StrictModeError(path, msg) {
msg = msg || 'Field `' + path + '` is not in schema and strict ' +
'mode is set to throw.';
MongooseError.call(this, msg);
this.name = 'StrictModeError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
this.path = path;
}
/*!
* Inherits from MongooseError.
*/
StrictModeError.prototype = Object.create(MongooseError.prototype);
StrictModeError.prototype.constructor = MongooseError;
module.exports = StrictModeError;
+112
View File
@@ -0,0 +1,112 @@
/*!
* Module requirements
*/
'use strict';
const MongooseError = require('./');
const util = require('util');
/**
* Document Validation Error
*
* @api private
* @param {Document} instance
* @inherits MongooseError
*/
function ValidationError(instance) {
this.errors = {};
this._message = '';
if (instance && instance.constructor.name === 'model') {
this._message = instance.constructor.modelName + ' validation failed';
MongooseError.call(this, this._message);
} else {
this._message = 'Validation failed';
MongooseError.call(this, this._message);
}
this.name = 'ValidationError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
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() {
return this.name + ': ' + _generateMessage(this);
};
/*!
* inspect helper
*/
ValidationError.prototype.inspect = function() {
return Object.assign(new Error(this.message), this);
};
if (util.inspect.custom) {
/*!
* Avoid Node deprecation warning DEP0079
*/
ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect;
}
/*!
* Helper for JSON.stringify
*/
ValidationError.prototype.toJSON = function() {
return Object.assign({}, this, { message: this.message });
};
/*!
* add message
*/
ValidationError.prototype.addError = function(path, error) {
this.errors[path] = error;
this.message = this._message + ': ' + _generateMessage(this);
};
/*!
* ignore
*/
function _generateMessage(err) {
const keys = Object.keys(err.errors || {});
const len = keys.length;
const msgs = [];
let key;
for (let i = 0; i < len; ++i) {
key = keys[i];
if (err === err.errors[key]) {
continue;
}
msgs.push(key + ': ' + err.errors[key].message);
}
return msgs.join(', ');
}
/*!
* Module exports
*/
module.exports = exports = ValidationError;
+89
View File
@@ -0,0 +1,89 @@
/*!
* Module dependencies.
*/
'use strict';
const MongooseError = require('./');
/**
* Schema validator error
*
* @param {Object} properties
* @inherits MongooseError
* @api private
*/
function ValidatorError(properties) {
let msg = properties.message;
if (!msg) {
msg = MongooseError.messages.general.default;
}
const message = this.formatMessage(msg, properties);
MongooseError.call(this, message);
properties = Object.assign({}, properties, { message: message });
this.name = 'ValidatorError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this);
} else {
this.stack = new Error().stack;
}
this.properties = properties;
this.kind = properties.type;
this.path = properties.path;
this.value = properties.value;
this.reason = properties.reason;
}
/*!
* Inherits from MongooseError
*/
ValidatorError.prototype = Object.create(MongooseError.prototype);
ValidatorError.prototype.constructor = MongooseError;
/*!
* The object used to define this validator. Not enumerable to hide
* it from `require('util').inspect()` output re: gh-3925
*/
Object.defineProperty(ValidatorError.prototype, 'properties', {
enumerable: false,
writable: true,
value: null
});
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function(msg, properties) {
if (typeof msg === 'function') {
return msg(properties);
}
const propertyNames = Object.keys(properties);
for (let i = 0; i < propertyNames.length; ++i) {
const 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;
+36
View File
@@ -0,0 +1,36 @@
'use strict';
/*!
* Module dependencies.
*/
const MongooseError = require('./');
/**
* Version Error constructor.
*
* @inherits MongooseError
* @api private
*/
function VersionError(doc, currentVersion, modifiedPaths) {
const modifiedPathsStr = modifiedPaths.join(', ');
MongooseError.call(this, 'No matching document found for id "' + doc._id +
'" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"');
this.name = 'VersionError';
this.version = currentVersion;
this.modifiedPaths = modifiedPaths;
}
/*!
* Inherits from MongooseError.
*/
VersionError.prototype = Object.create(MongooseError.prototype);
VersionError.prototype.constructor = MongooseError;
/*!
* exports
*/
module.exports = VersionError;
Loaded 100 of 2409 files, more files were not shown because too many files have changed in this diff. Show more