Update Node_modules
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
language: node_js
|
||||
sudo: false
|
||||
node_js: [11, 10, 9, 8, 7, 6, 5, 4]
|
||||
node_js: [12, 11, 10, 9, 8, 7, 6, 5, 4]
|
||||
install:
|
||||
- travis_retry npm install
|
||||
before_script:
|
||||
|
||||
+108
-1
@@ -1,3 +1,110 @@
|
||||
5.6.2 / 2019-06-28
|
||||
==================
|
||||
* fix(update): allow using `update()` with immutable `createdAt` #7917
|
||||
* fix(model): pass `doc` parameter to save() error handling middleware #7832
|
||||
* fix(mongoose): add applyPluginsToChildSchemas option to allow opting out of global plugins for child schemas #7916
|
||||
* docs(connection): document `useCache` option for `useDb()` #7923
|
||||
* docs: fix broken link in FAQ #7925 [christophergeiger3](https://github.com/christophergeiger3)
|
||||
|
||||
5.6.1 / 2019-06-24
|
||||
==================
|
||||
* fix(update): skip setting defaults for single embedded subdocs underneath maps #7909
|
||||
* fix(document): copy date objects correctly when strict = false #7907
|
||||
* feat(mongoose): throw an error if calling `mongoose.connect()` multiple times while connected #7905 [Fonger](https://github.com/Fonger)
|
||||
* fix(document): copies virtuals from array subdocs when casting array of docs with same schema #7898
|
||||
* fix(schema): ensure clone() copies single embedded discriminators correctly #7894
|
||||
* fix(discriminator): merge instead of overwriting conflicting nested schemas in discriminator schema #7884
|
||||
* fix(populate): ignore nullish arguments when calling `populate()` #7913 [rayhatfield](https://github.com/rayhatfield)
|
||||
* docs: add getters/setters tutorial #7919
|
||||
* docs: clean up error docs so they refer to `Error` rather than `MongooseError` #7867
|
||||
* docs: fix a couple broken links #7921 [kizmo04](https://github.com/kizmo04)
|
||||
* refactor: remove unnecessary if #7911 [rayhatfield](https://github.com/rayhatfield)
|
||||
|
||||
5.6.0 / 2019-06-14
|
||||
==================
|
||||
* feat(schematype): add `immutable` option to disallow changing a given field #7671
|
||||
* docs: split API docs into separate pages to make API documentation more Google-able #7812
|
||||
* perf(array): remove all mixins in favor of ES6 classes, ~20% faster in basic benchmarks #7798
|
||||
* feat(document): use promise rejection error message when async custom validator throws an error #4913
|
||||
* feat(virtual): pass document as 3rd parameter to virtual getters and setters to enable using arrow functions #4143
|
||||
* feat(model): add `Model.exists()` function to quickly check whether a document matching `filter` exists #6872
|
||||
* feat(index+connection): support setting global and connection-level `maxTimeMS`
|
||||
* feat(populate): support setting `ref` to a function for conventional populate #7669
|
||||
* feat(document): add overwrite() function that overwrites all values in a document #7830
|
||||
* feat(populate): support `PopulateOptions#connection` option to allow cross-db populate with refPath #6520
|
||||
* feat(populate): add skipInvalidIds option to silently skip population if id is invalid, instead of throwing #7706
|
||||
* feat(array): skip empty array default if there's a 2dsphere index on a geojson path #3233
|
||||
* feat(query): add `getFilter()` as an alias of `getQuery()` to be more in line with API docs #7839
|
||||
* feat(model): add Model.inspect() to make models not clutter `util.inspect()` #7836
|
||||
* perf(discriminator): skip calling `createIndex()` on indexes that are defined in the base schema #7379
|
||||
* docs: upgrade from Jade to latest Pug #7812
|
||||
* docs(README): update reference to example schema.js #7899 [sharils](https://github.com/sharils)
|
||||
* docs(README): improve variable name #7900 [sharils](https://github.com/sharils)
|
||||
* chore: replace charAt(0) with startsWith #7897 [Fonger](https://github.com/Fonger)
|
||||
* chore: replace indexOf with includes, startsWith and endsWith for String #7897 [Fonger](https://github.com/Fonger)
|
||||
|
||||
5.5.15 / 2019-06-12
|
||||
===================
|
||||
* fix(connection): reject initial connect promise even if there is an on('error') listener #7850
|
||||
* fix(map): make `of` automatically convert POJOs to schemas unless typeKey is set #7859
|
||||
* fix(update): use discriminator schema to cast update if discriminator key specified in filter #7843
|
||||
* fix(array): copy atomics from source array #7891 #7889 [jyrkive](https://github.com/jyrkive)
|
||||
* fix(schema): return this when Schema.prototype.add is called with Schema #7887 [Mickael-van-der-Beek](https://github.com/Mickael-van-der-Beek)
|
||||
* fix(document): add `numAffected` and `result` to DocumentNotFoundError for better debugging #7892 #7844
|
||||
|
||||
5.5.14 / 2019-06-08
|
||||
===================
|
||||
* fix(query): correct this scope of setters in update query #7876 [Fonger](https://github.com/Fonger)
|
||||
* fix(model): reset modifiedPaths after successful insertMany #7852 #7873 [Fonger](https://github.com/Fonger)
|
||||
* fix(populate): allow using `refPath` with virtual populate #7848
|
||||
* fix(document): prepend private methods getValue and setValue with $ #7870 [Fonger](https://github.com/Fonger)
|
||||
* fix: update mongodb driver -> 3.2.7 #7871 [Fonger](https://github.com/Fonger)
|
||||
* docs(tutorials): add tutorial about custom casting functions #7045
|
||||
* docs(connection): fix outdated events document #7874 [Fonger](https://github.com/Fonger)
|
||||
* docs: fix typo in lean docs #7875 [tannakartikey](https://github.com/tannakartikey)
|
||||
* docs: move off of KeenIO for tracking and use self-hosted analytics instead
|
||||
|
||||
5.5.13 / 2019-06-05
|
||||
===================
|
||||
* fix(model): support passing deleteOne options #7860 #7857 [Fonger](https://github.com/Fonger)
|
||||
* fix(update): run setters on array elements when doing $addToSet, $push, etc #4185
|
||||
* fix(model): support getting discriminator by value when creating a new model #7851
|
||||
* docs(transactions): add section about the `withTransaction()` helper #7598
|
||||
* docs(schema): clarify relationship between Schema#static() and Schema#statics #7827
|
||||
* docs(model): fix typo `projetion` to `projection` #7868 [dfdeagle47](https://github.com/dfdeagle47)
|
||||
* docs(schema): correct schema options lists #7828
|
||||
|
||||
5.5.12 / 2019-05-31
|
||||
===================
|
||||
* fix(document): fix unexpected error when loading a document with a nested property named `schema` #7831
|
||||
* fix(model): skip applying static hooks by default if static name conflicts with query middleware (re: mongoose-delete plugin) #7790
|
||||
* fix(query): apply schema-level projections to the result of `findOneAndReplace()` #7654
|
||||
* fix: upgrade mongodb driver -> 3.2.6
|
||||
* docs(tutorials): add findOneAndUpdate() tutorial #7847
|
||||
* docs(validation): add `updateOne()` and `updateMany()` to list of update validator operations #7845
|
||||
* docs(model): make sure options lists in `update()` API line up #7842
|
||||
|
||||
5.5.11 / 2019-05-23
|
||||
===================
|
||||
* fix(discriminator): allow numeric discriminator keys for embedded discriminators #7808
|
||||
* chore: add Node.js 12 to travis build matrix #7784
|
||||
|
||||
5.5.10 / 2019-05-20
|
||||
===================
|
||||
* fix(discriminator): allow user-defined discriminator path in schema #7807
|
||||
* fix(query): ensure `findOneAndReplace()` sends `replacement` to server #7654
|
||||
* fix(cast): allow `[]` as a value when casting `$nin` #7806
|
||||
* docs(model): clarify that setters do run on `update()` by default #7801
|
||||
* docs: fix typo in FAQ #7821 [jaona](https://github.com/jaona)
|
||||
|
||||
5.5.9 / 2019-05-16
|
||||
==================
|
||||
* fix(query): skip schema setters when casting $regexp $options #7802 [Fonger](https://github.com/Fonger)
|
||||
* fix(populate): don't skip populating doc array properties whose name conflicts with an array method #7782
|
||||
* fix(populate): make populated virtual return undefined if not populated #7795
|
||||
* fix(schema): handle custom setters in arrays of document arrays #7804 [Fonger](https://github.com/Fonger)
|
||||
* docs(tutorials): add query casting tutorial #7789
|
||||
|
||||
5.5.8 / 2019-05-13
|
||||
==================
|
||||
* fix(document): run pre save hooks on nested child schemas #7792
|
||||
@@ -137,7 +244,7 @@
|
||||
|
||||
5.4.19 / 2019-03-11
|
||||
===================
|
||||
* fix(mongoose): ensure virtuals set on subdocs in global plugins get applied #7592
|
||||
* fix(mongoose): ensure virtuals set on subdocs in global plugins get applied #7572
|
||||
* docs(tutorials): add "Working With Dates" tutorial #7597
|
||||
* docs(guide): clarify that versioning only affects array fields #7555
|
||||
* docs(model): list out all bulkWrite() options #7550
|
||||
|
||||
+6
-6
@@ -43,9 +43,9 @@ branch and follow the [contributing guide](https://github.com/Automattic/mongoos
|
||||
|
||||
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`.
|
||||
your changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`.
|
||||
|
||||
View all 300+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).
|
||||
View all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors).
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -127,14 +127,14 @@ Comment.pre('save', function (next) {
|
||||
});
|
||||
```
|
||||
|
||||
Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup.
|
||||
Take a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/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');
|
||||
const MyModel = mongoose.model('ModelName');
|
||||
```
|
||||
|
||||
Or just do it all at once
|
||||
@@ -201,10 +201,10 @@ Where `Comment` is a `Schema` we created. This means that creating embedded docu
|
||||
|
||||
```js
|
||||
// retrieve my model
|
||||
var BlogPost = mongoose.model('BlogPost');
|
||||
const BlogPost = mongoose.model('BlogPost');
|
||||
|
||||
// create a blog post
|
||||
var post = new BlogPost();
|
||||
const post = new BlogPost();
|
||||
|
||||
// create a comment
|
||||
post.comments.push({ title: 'My comment' });
|
||||
|
||||
+6
-3
@@ -6,6 +6,7 @@
|
||||
|
||||
const AggregationCursor = require('./cursor/AggregationCursor');
|
||||
const Query = require('./query');
|
||||
const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS');
|
||||
const util = require('util');
|
||||
const utils = require('./utils');
|
||||
const read = Query.prototype.read;
|
||||
@@ -373,7 +374,7 @@ Aggregate.prototype.unwind = function() {
|
||||
res.push({ $unwind: arg });
|
||||
} else if (typeof arg === 'string') {
|
||||
res.push({
|
||||
$unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg
|
||||
$unwind: (arg && arg.startsWith('$')) ? arg : '$' + arg
|
||||
});
|
||||
} else {
|
||||
throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
|
||||
@@ -459,7 +460,7 @@ Aggregate.prototype.sortByCount = function(arg) {
|
||||
return this.append({ $sortByCount: arg });
|
||||
} else if (typeof arg === 'string') {
|
||||
return this.append({
|
||||
$sortByCount: (arg && arg.charAt(0) === '$') ? arg : '$' + arg
|
||||
$sortByCount: (arg && arg.startsWith('$')) ? arg : '$' + arg
|
||||
});
|
||||
} else {
|
||||
throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), ' +
|
||||
@@ -510,7 +511,7 @@ Aggregate.prototype.graphLookup = function(options) {
|
||||
const startWith = cloneOptions.startWith;
|
||||
|
||||
if (startWith && typeof startWith === 'string') {
|
||||
cloneOptions.startWith = cloneOptions.startWith.charAt(0) === '$' ?
|
||||
cloneOptions.startWith = cloneOptions.startWith.startsWith('$') ?
|
||||
cloneOptions.startWith :
|
||||
'$' + cloneOptions.startWith;
|
||||
}
|
||||
@@ -932,6 +933,8 @@ Aggregate.prototype.exec = function(callback) {
|
||||
const pipeline = this._pipeline;
|
||||
const collection = this._model.collection;
|
||||
|
||||
applyGlobalMaxTimeMS(this.options, model);
|
||||
|
||||
if (this.options && this.options.cursor) {
|
||||
return new AggregationCursor(this);
|
||||
}
|
||||
|
||||
+4
-4
@@ -237,7 +237,7 @@ module.exports = function cast(schema, obj, options, context) {
|
||||
'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.');
|
||||
'schema and strictQuery is \'throw\'.');
|
||||
} else if (options.strictQuery) {
|
||||
delete obj[path];
|
||||
}
|
||||
@@ -245,7 +245,7 @@ module.exports = function cast(schema, obj, options, context) {
|
||||
continue;
|
||||
} else if (val.constructor.name === 'Object') {
|
||||
any$conditionals = Object.keys(val).some(function(k) {
|
||||
return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
|
||||
return k.startsWith('$') && k !== '$id' && k !== '$ref';
|
||||
});
|
||||
|
||||
if (!any$conditionals) {
|
||||
@@ -266,7 +266,7 @@ module.exports = function cast(schema, obj, options, context) {
|
||||
if ($cond === '$not') {
|
||||
if (nested && schematype && !schematype.caster) {
|
||||
_keys = Object.keys(nested);
|
||||
if (_keys.length && _keys[0].charAt(0) === '$') {
|
||||
if (_keys.length && _keys[0].startsWith('$')) {
|
||||
for (const key in nested) {
|
||||
nested[key] = schematype.castForQueryWrapper({
|
||||
$conditional: key,
|
||||
@@ -337,4 +337,4 @@ function _cast(val, numbertype, context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+50
-11
@@ -40,10 +40,9 @@ const noPasswordAuthMechanisms = [
|
||||
* @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 `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful 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.
|
||||
* @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string.
|
||||
* @api public
|
||||
*/
|
||||
|
||||
@@ -61,9 +60,6 @@ function Connection(base) {
|
||||
this._closeCalled = false;
|
||||
this._hasOpened = false;
|
||||
this.plugins = [];
|
||||
|
||||
this.$internalEmitter = new EventEmitter();
|
||||
this.$internalEmitter.setMaxListeners(0);
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -123,6 +119,48 @@ Object.defineProperty(Connection.prototype, 'readyState', {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Gets the value of the option `key`. Equivalent to `conn.options[key]`
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* conn.get('test'); // returns the 'test' value
|
||||
*
|
||||
* @param {String} key
|
||||
* @method get
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.get = function(key) {
|
||||
return get(this.options, key);
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the value of the option `key`. Equivalent to `conn.options[key] = val`
|
||||
*
|
||||
* Supported options include:
|
||||
*
|
||||
* - `maxTimeMS`: Set [`maxTimeMS`](/docs/api.html#query_Query-maxTimeMS) for all queries on this connection.
|
||||
* - `useFindAndModify`: Set to `false` to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#-findandmodify-)
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* conn.set('test', 'foo');
|
||||
* conn.get('test'); // 'foo'
|
||||
* conn.options.test; // 'foo'
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {Any} val
|
||||
* @method set
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Connection.prototype.set = function(key, val) {
|
||||
this.options = this.options || {};
|
||||
this.options[key] = val;
|
||||
return val;
|
||||
};
|
||||
|
||||
/**
|
||||
* A hash of the collections associated with this connection
|
||||
*
|
||||
@@ -622,7 +660,6 @@ Connection.prototype.openUri = function(uri, options, callback) {
|
||||
catch(err => {
|
||||
if (this.listeners('error').length > 0) {
|
||||
process.nextTick(() => this.emit('error', err));
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
@@ -689,11 +726,11 @@ Connection.prototype._close = function(force, callback) {
|
||||
this._closeCalled = true;
|
||||
|
||||
switch (this.readyState) {
|
||||
case 0: // disconnected
|
||||
case STATES.disconnected:
|
||||
callback();
|
||||
break;
|
||||
|
||||
case 1: // connected
|
||||
case STATES.connected:
|
||||
this.readyState = STATES.disconnecting;
|
||||
this.doClose(force, function(err) {
|
||||
if (err) {
|
||||
@@ -704,13 +741,13 @@ Connection.prototype._close = function(force, callback) {
|
||||
});
|
||||
|
||||
break;
|
||||
case 2: // connecting
|
||||
case STATES.connecting:
|
||||
this.once('open', function() {
|
||||
_this.close(callback);
|
||||
});
|
||||
break;
|
||||
|
||||
case 3: // disconnecting
|
||||
case STATES.disconnecting:
|
||||
this.once('close', function() {
|
||||
callback();
|
||||
});
|
||||
@@ -1011,6 +1048,8 @@ Connection.prototype.optionsProvideAuthenticationData = function(options) {
|
||||
* @method useDb
|
||||
* @memberOf Connection
|
||||
* @param {String} name The database name
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
|
||||
* @return {Connection} New Connection Object
|
||||
* @api public
|
||||
*/
|
||||
|
||||
+63
-29
@@ -34,7 +34,9 @@ const isMongooseObject = utils.isMongooseObject;
|
||||
|
||||
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
|
||||
const documentArrayParent = require('./helpers/symbols').documentArrayParent;
|
||||
const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
|
||||
const getSymbol = require('./helpers/symbols').getSymbol;
|
||||
const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
|
||||
|
||||
let DocumentArray;
|
||||
let MongooseArray;
|
||||
@@ -718,6 +720,36 @@ Document.prototype.$session = function $session(session) {
|
||||
return session;
|
||||
};
|
||||
|
||||
/**
|
||||
* Overwrite all values in this document with the values of `obj`, except
|
||||
* for immutable properties. Behaves similarly to `set()`, except for it
|
||||
* unsets all properties that aren't in `obj`.
|
||||
*
|
||||
* @param {Object} obj the object to overwrite this document with
|
||||
* @method overwrite
|
||||
* @name overwrite
|
||||
* @memberOf Document
|
||||
* @instance
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Document.prototype.overwrite = function overwrite(obj) {
|
||||
const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
|
||||
|
||||
for (const key of keys) {
|
||||
if (key === '_id') {
|
||||
continue;
|
||||
}
|
||||
// Explicitly skip version key
|
||||
if (this.schema.options.versionKey && key === this.schema.options.versionKey) {
|
||||
continue;
|
||||
}
|
||||
this.$set(key, obj[key]);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Alias for `set()`, used internally to avoid conflicts
|
||||
*
|
||||
@@ -812,7 +844,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
||||
}
|
||||
|
||||
if (typeof path[key] === 'object' &&
|
||||
!Array.isArray(path[key]) &&
|
||||
!utils.isNativeObject(path[key]) &&
|
||||
path[key] != null &&
|
||||
pathtype !== 'virtual' &&
|
||||
pathtype !== 'real' &&
|
||||
@@ -871,14 +903,14 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
||||
if (pathType === 'nested' && val) {
|
||||
if (typeof val === 'object' && val != null) {
|
||||
if (!merge) {
|
||||
this.setValue(path, null);
|
||||
this.$__setValue(path, null);
|
||||
cleanModifiedSubpaths(this, path);
|
||||
} else {
|
||||
return this.$set(val, path, constructing);
|
||||
}
|
||||
|
||||
const keys = Object.keys(val);
|
||||
this.setValue(path, {});
|
||||
this.$__setValue(path, {});
|
||||
for (const key of keys) {
|
||||
this.$set(path + '.' + key, val[key], constructing);
|
||||
}
|
||||
@@ -958,7 +990,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
||||
if (!this.isSelected(curPath)) {
|
||||
this.unmarkModified(curPath);
|
||||
}
|
||||
cur = this.getValue(curPath);
|
||||
cur = this.$__getValue(curPath);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -986,12 +1018,12 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
||||
// if this doc is being constructed we should not trigger getters
|
||||
const priorVal = (() => {
|
||||
if (this.$__.$options.priorDoc != null) {
|
||||
return this.$__.$options.priorDoc.getValue(path);
|
||||
return this.$__.$options.priorDoc.$__getValue(path);
|
||||
}
|
||||
if (constructing) {
|
||||
return void 0;
|
||||
}
|
||||
return this.getValue(path);
|
||||
return this.$__getValue(path);
|
||||
})();
|
||||
|
||||
if (!schema) {
|
||||
@@ -1034,9 +1066,9 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
||||
if (refMatches && val instanceof Document) {
|
||||
if (this.ownerDocument) {
|
||||
this.ownerDocument().populated(this.$__fullPath(path),
|
||||
val._id, {model: val.constructor});
|
||||
val._id, { [populateModelSymbol]: val.constructor });
|
||||
} else {
|
||||
this.populated(path, val._id, {model: val.constructor});
|
||||
this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
|
||||
}
|
||||
didPopulate = true;
|
||||
}
|
||||
@@ -1052,11 +1084,11 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
||||
val[0].constructor.modelName &&
|
||||
(schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.baseModelName || schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.modelName)) {
|
||||
if (this.ownerDocument) {
|
||||
popOpts = { model: val[0].constructor };
|
||||
popOpts = { [populateModelSymbol]: val[0].constructor };
|
||||
this.ownerDocument().populated(this.$__fullPath(path),
|
||||
val.map(function(v) { return v._id; }), popOpts);
|
||||
} else {
|
||||
popOpts = { model: val[0].constructor };
|
||||
popOpts = { [populateModelSymbol]: val[0].constructor };
|
||||
this.populated(path, val.map(function(v) { return v._id; }), popOpts);
|
||||
}
|
||||
didPopulate = true;
|
||||
@@ -1220,7 +1252,7 @@ Document.prototype.$__set = function(pathToMark, path, constructing, parts, sche
|
||||
// Small hack for gh-1638: if we're overwriting the entire array, ignore
|
||||
// paths that were modified before the array overwrite
|
||||
this.$__.activePaths.forEach(function(modifiedPath) {
|
||||
if (modifiedPath.indexOf(path + '.') === 0) {
|
||||
if (modifiedPath.startsWith(path + '.')) {
|
||||
_this.$__.activePaths.ignore(modifiedPath);
|
||||
}
|
||||
});
|
||||
@@ -1270,7 +1302,7 @@ Document.prototype.$__set = function(pathToMark, path, constructing, parts, sche
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Document.prototype.getValue = function(path) {
|
||||
Document.prototype.$__getValue = function(path) {
|
||||
return utils.getValue(path, this._doc);
|
||||
};
|
||||
|
||||
@@ -1282,7 +1314,7 @@ Document.prototype.getValue = function(path) {
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Document.prototype.setValue = function(path, val) {
|
||||
Document.prototype.$__setValue = function(path, val) {
|
||||
utils.setValue(path, val, this._doc);
|
||||
return this;
|
||||
};
|
||||
@@ -1624,7 +1656,7 @@ Document.prototype.isModified = function(paths, modifiedPaths) {
|
||||
});
|
||||
return isModifiedChild || paths.some(function(path) {
|
||||
return directModifiedPaths.some(function(mod) {
|
||||
return mod === path || path.indexOf(mod + '.') === 0;
|
||||
return mod === path || path.startsWith(mod + '.');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1772,11 +1804,11 @@ Document.prototype.isSelected = function isSelected(path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cur.indexOf(pathDot) === 0) {
|
||||
if (cur.startsWith(pathDot)) {
|
||||
return inclusive || cur !== pathDot;
|
||||
}
|
||||
|
||||
if (pathDot.indexOf(cur + '.') === 0) {
|
||||
if (pathDot.startsWith(cur + '.')) {
|
||||
return inclusive;
|
||||
}
|
||||
}
|
||||
@@ -1954,7 +1986,7 @@ function _getPathsToValidate(doc) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const val = doc.getValue(path);
|
||||
const val = doc.$__getValue(path);
|
||||
if (val) {
|
||||
const numElements = val.length;
|
||||
for (let j = 0; j < numElements; ++j) {
|
||||
@@ -1968,7 +2000,7 @@ function _getPathsToValidate(doc) {
|
||||
for (i = 0; i < len; ++i) {
|
||||
const pathToCheck = paths[i];
|
||||
if (doc.schema.nested[pathToCheck]) {
|
||||
let _v = doc.getValue(pathToCheck);
|
||||
let _v = doc.$__getValue(pathToCheck);
|
||||
if (isMongooseObject(_v)) {
|
||||
_v = _v.toObject({ transform: false });
|
||||
}
|
||||
@@ -1988,7 +2020,7 @@ function _getPathsToValidate(doc) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const val = doc.getValue(path);
|
||||
const val = doc.$__getValue(path);
|
||||
if (val == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -2093,7 +2125,7 @@ Document.prototype.$__validate = function(options, callback) {
|
||||
return;
|
||||
}
|
||||
|
||||
const val = _this.getValue(path);
|
||||
const val = _this.$__getValue(path);
|
||||
const scope = path in _this.$__.pathsToScopes ?
|
||||
_this.$__.pathsToScopes[path] :
|
||||
_this;
|
||||
@@ -2191,7 +2223,7 @@ Document.prototype.validateSync = function(pathsToValidate, options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const val = _this.getValue(path);
|
||||
const val = _this.$__getValue(path);
|
||||
const err = p.doValidateSync(val, _this, {
|
||||
skipSchemaValidators: skipSchemaValidators[path],
|
||||
path: path
|
||||
@@ -2364,7 +2396,7 @@ Document.prototype.$__reset = function reset() {
|
||||
|
||||
this.$__.activePaths
|
||||
.map('init', 'modify', function(i) {
|
||||
return _this.getValue(i);
|
||||
return _this.$__getValue(i);
|
||||
})
|
||||
.filter(function(val) {
|
||||
return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
|
||||
@@ -2386,7 +2418,7 @@ Document.prototype.$__reset = function reset() {
|
||||
|
||||
this.$__.activePaths.
|
||||
map('init', 'modify', function(i) {
|
||||
return _this.getValue(i);
|
||||
return _this.$__getValue(i);
|
||||
}).
|
||||
filter(function(val) {
|
||||
return val && val.$isSingleNested;
|
||||
@@ -2433,7 +2465,7 @@ Document.prototype.$__dirty = function() {
|
||||
let all = this.$__.activePaths.map('modify', function(path) {
|
||||
return {
|
||||
path: path,
|
||||
value: _this.getValue(path),
|
||||
value: _this.$__getValue(path),
|
||||
schema: _this.$__path(path)
|
||||
};
|
||||
});
|
||||
@@ -2441,12 +2473,12 @@ Document.prototype.$__dirty = function() {
|
||||
// gh-2558: if we had to set a default and the value is not undefined,
|
||||
// we have to save as well
|
||||
all = all.concat(this.$__.activePaths.map('default', function(path) {
|
||||
if (path === '_id' || _this.getValue(path) == null) {
|
||||
if (path === '_id' || _this.$__getValue(path) == null) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
path: path,
|
||||
value: _this.getValue(path),
|
||||
value: _this.$__getValue(path),
|
||||
schema: _this.$__path(path)
|
||||
};
|
||||
}));
|
||||
@@ -2506,6 +2538,7 @@ Document.prototype.$__setSchema = function(schema) {
|
||||
}
|
||||
|
||||
this.schema = schema;
|
||||
this[documentSchemaSymbol] = schema;
|
||||
};
|
||||
|
||||
|
||||
@@ -2524,7 +2557,7 @@ Document.prototype.$__getArrayPathsToValidate = function() {
|
||||
// validate all document arrays.
|
||||
return this.$__.activePaths
|
||||
.map('init', 'modify', function(i) {
|
||||
return this.getValue(i);
|
||||
return this.$__getValue(i);
|
||||
}.bind(this))
|
||||
.filter(function(val) {
|
||||
return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
|
||||
@@ -2553,7 +2586,7 @@ Document.prototype.$__getAllSubdocs = function() {
|
||||
function docReducer(doc, seed, path) {
|
||||
let val = doc;
|
||||
if (path) {
|
||||
if (doc instanceof Document && doc.schema.paths[path]) {
|
||||
if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) {
|
||||
val = doc._doc[path];
|
||||
} else {
|
||||
val = doc[path];
|
||||
@@ -2852,7 +2885,7 @@ Document.prototype.$toObject = function(options, json) {
|
||||
*
|
||||
* Transforms are applied _only to the document and are not applied to sub-documents_.
|
||||
*
|
||||
* Transforms, like all of these options, are also available for `toJSON`.
|
||||
* Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions.
|
||||
*
|
||||
* See [schema options](/docs/guide.html#toObject) for some more details.
|
||||
*
|
||||
@@ -3014,6 +3047,7 @@ function applyGetters(self, json, type, options) {
|
||||
* @param {Object} options
|
||||
* @return {Object}
|
||||
* @see Document#toObject #document_Document-toObject
|
||||
* @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html
|
||||
* @api public
|
||||
* @memberOf Document
|
||||
* @instance
|
||||
|
||||
+4
-1
@@ -35,9 +35,12 @@ NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
|
||||
/**
|
||||
* Switches to a different database using the same connection pool.
|
||||
*
|
||||
* Returns a new connection object, with the new db.
|
||||
* Returns a new connection object, with the new db. If you set the `useCache`
|
||||
* option, `useDb()` will cache connections by `name`.
|
||||
*
|
||||
* @param {String} name The database name
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
|
||||
* @return {Connection} New Connection Object
|
||||
* @api public
|
||||
*/
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ const util = require('util');
|
||||
function CastError(type, value, path, reason) {
|
||||
let stringValue = util.inspect(value);
|
||||
stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"');
|
||||
if (stringValue.charAt(0) !== '"') {
|
||||
if (!stringValue.startsWith('"')) {
|
||||
stringValue = '"' + stringValue + '"';
|
||||
}
|
||||
MongooseError.call(this, 'Cast to ' + type + ' failed for value ' +
|
||||
|
||||
+62
@@ -1,7 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* MongooseError constructor. MongooseError is the base class for all
|
||||
* Mongoose-specific errors.
|
||||
*
|
||||
* ####Example:
|
||||
* const Model = mongoose.model('Test', new Schema({ answer: Number }));
|
||||
* const doc = new Model({ answer: 'not a number' });
|
||||
* const err = doc.validateSync();
|
||||
*
|
||||
* err instanceof mongoose.Error; // true
|
||||
*
|
||||
* @constructor Error
|
||||
* @param {String} msg Error message
|
||||
* @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
|
||||
*/
|
||||
|
||||
const MongooseError = require('./mongooseError');
|
||||
|
||||
/**
|
||||
* The name of the error. The name uniquely identifies this Mongoose error. The
|
||||
* possible values are:
|
||||
*
|
||||
* - `MongooseError`: general Mongoose error
|
||||
* - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property.
|
||||
* - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect.
|
||||
* - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection
|
||||
* - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined
|
||||
* - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found
|
||||
* - `ValidatorError`: error from an individual schema path's validator
|
||||
* - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property.
|
||||
* - `MissingSchemaError`: You called `mongoose.Document()` without a schema
|
||||
* - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict).
|
||||
* - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter
|
||||
* - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined.
|
||||
* - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving.
|
||||
* - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`.
|
||||
* - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey)
|
||||
*
|
||||
* @api public
|
||||
* @property {String} name
|
||||
* @memberOf Error
|
||||
* @instance
|
||||
*/
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
@@ -13,6 +55,8 @@ module.exports = exports = MongooseError;
|
||||
*
|
||||
* @see Error.messages #error_messages_MongooseError-messages
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static messages
|
||||
*/
|
||||
|
||||
MongooseError.messages = require('./messages');
|
||||
@@ -28,6 +72,8 @@ MongooseError.Messages = MongooseError.messages;
|
||||
* the document.
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static DocumentNotFoundError
|
||||
*/
|
||||
|
||||
MongooseError.DocumentNotFoundError = require('./notFound');
|
||||
@@ -37,6 +83,8 @@ MongooseError.DocumentNotFoundError = require('./notFound');
|
||||
* cast a value.
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static CastError
|
||||
*/
|
||||
|
||||
MongooseError.CastError = require('./cast');
|
||||
@@ -47,6 +95,8 @@ MongooseError.CastError = require('./cast');
|
||||
* instances of CastError or ValidationError.
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static ValidationError
|
||||
*/
|
||||
|
||||
MongooseError.ValidationError = require('./validation');
|
||||
@@ -55,6 +105,8 @@ MongooseError.ValidationError = require('./validation');
|
||||
* A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static ValidatorError
|
||||
*/
|
||||
|
||||
MongooseError.ValidatorError = require('./validator');
|
||||
@@ -65,6 +117,8 @@ MongooseError.ValidatorError = require('./validator');
|
||||
* the [`versionKey` option](/docs/guide.html#versionKey) for more information.
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static VersionError
|
||||
*/
|
||||
|
||||
MongooseError.VersionError = require('./version');
|
||||
@@ -75,6 +129,8 @@ MongooseError.VersionError = require('./version');
|
||||
* information.
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static ParallelSaveError
|
||||
*/
|
||||
|
||||
MongooseError.ParallelSaveError = require('./parallelSave');
|
||||
@@ -84,6 +140,8 @@ MongooseError.ParallelSaveError = require('./parallelSave');
|
||||
* See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error).
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static OverwriteModelError
|
||||
*/
|
||||
|
||||
MongooseError.OverwriteModelError = require('./overwriteModel');
|
||||
@@ -92,6 +150,8 @@ MongooseError.OverwriteModelError = require('./overwriteModel');
|
||||
* Thrown when you try to access a model that has not been registered yet
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static MissingSchemaError
|
||||
*/
|
||||
|
||||
MongooseError.MissingSchemaError = require('./missingSchema');
|
||||
@@ -101,6 +161,8 @@ MongooseError.MissingSchemaError = require('./missingSchema');
|
||||
* and then modified the array in an unsafe way.
|
||||
*
|
||||
* @api public
|
||||
* @memberOf Error
|
||||
* @static DivergentArrayError
|
||||
*/
|
||||
|
||||
MongooseError.DivergentArrayError = require('./divergentArray');
|
||||
|
||||
+2
-32
@@ -1,11 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* MongooseError constructor. MongooseError is the base class for all
|
||||
* Mongoose-specific errors.
|
||||
*
|
||||
* @param {String} msg Error message
|
||||
* @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function MongooseError(msg) {
|
||||
@@ -26,30 +22,4 @@ function MongooseError(msg) {
|
||||
MongooseError.prototype = Object.create(Error.prototype);
|
||||
MongooseError.prototype.constructor = Error;
|
||||
|
||||
/**
|
||||
* The name of the error. The name uniquely identifies this Mongoose error. The
|
||||
* possible values are:
|
||||
*
|
||||
* - `MongooseError`: general Mongoose error
|
||||
* - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property.
|
||||
* - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect.
|
||||
* - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection
|
||||
* - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined
|
||||
* - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found
|
||||
* - `ValidatorError`: error from an individual schema path's validator
|
||||
* - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property.
|
||||
* - `MissingSchemaError`: You called `mongoose.Document()` without a schema
|
||||
* - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict).
|
||||
* - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter
|
||||
* - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined.
|
||||
* - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving.
|
||||
* - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`.
|
||||
* - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey)
|
||||
*
|
||||
* @api public
|
||||
* @property {String} name
|
||||
* @memberOf MongooseError
|
||||
* @instance
|
||||
*/
|
||||
|
||||
module.exports = MongooseError;
|
||||
|
||||
+6
-3
@@ -13,20 +13,23 @@ const util = require('util');
|
||||
* @inherits MongooseError
|
||||
*/
|
||||
|
||||
function DocumentNotFoundError(filter) {
|
||||
function DocumentNotFoundError(filter, model, numAffected, result) {
|
||||
let msg;
|
||||
const messages = MongooseError.messages;
|
||||
if (messages.DocumentNotFoundError != null) {
|
||||
msg = typeof messages.DocumentNotFoundError === 'function' ?
|
||||
messages.DocumentNotFoundError(filter) :
|
||||
messages.DocumentNotFoundError(filter, model) :
|
||||
messages.DocumentNotFoundError;
|
||||
} else {
|
||||
msg = 'No document found for query "' + util.inspect(filter) + '"';
|
||||
msg = 'No document found for query "' + util.inspect(filter) +
|
||||
'" on model "' + model + '"';
|
||||
}
|
||||
|
||||
MongooseError.call(this, msg);
|
||||
|
||||
this.name = 'DocumentNotFoundError';
|
||||
this.result = result;
|
||||
this.numAffected = numAffected;
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this);
|
||||
} else {
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
const getDiscriminatorByValue = require('../../queryhelpers').getDiscriminatorByValue;
|
||||
|
||||
/*!
|
||||
* Find the correct constructor, taking into account discriminators
|
||||
*/
|
||||
|
||||
module.exports = function getConstructor(Constructor, value) {
|
||||
const discriminatorKey = Constructor.schema.options.discriminatorKey;
|
||||
if (value != null &&
|
||||
Constructor.discriminators &&
|
||||
value[discriminatorKey] != null) {
|
||||
if (Constructor.discriminators[value[discriminatorKey]]) {
|
||||
Constructor = Constructor.discriminators[value[discriminatorKey]];
|
||||
} else {
|
||||
const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]);
|
||||
if (constructorByValue) {
|
||||
Constructor = constructorByValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Constructor;
|
||||
};
|
||||
+1
-1
@@ -19,7 +19,7 @@ module.exports = function cleanModifiedSubpaths(doc, path, options) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (modifiedPath.indexOf(path + '.') === 0) {
|
||||
if (modifiedPath.startsWith(path + '.')) {
|
||||
delete doc.$__.activePaths.states.modify[modifiedPath];
|
||||
++deleted;
|
||||
}
|
||||
|
||||
+8
@@ -1,5 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol;
|
||||
const get = require('../../helpers/get');
|
||||
const getSymbol = require('../../helpers/symbols').getSymbol;
|
||||
const utils = require('../../utils');
|
||||
@@ -71,6 +72,13 @@ function defineKey(prop, subprops, prototype, prefix, keys, options) {
|
||||
value: prototype.schema
|
||||
});
|
||||
|
||||
Object.defineProperty(nested, documentSchemaSymbol, {
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
writable: false,
|
||||
value: prototype.schema
|
||||
});
|
||||
|
||||
Object.defineProperty(nested, 'toObject', {
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
|
||||
+12
-2
@@ -1,5 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
const middlewareFunctions = require('../query/applyQueryMiddleware').middlewareFunctions;
|
||||
const utils = require('../../utils');
|
||||
|
||||
module.exports = function applyStaticHooks(model, hooks, statics) {
|
||||
@@ -8,7 +9,16 @@ module.exports = function applyStaticHooks(model, hooks, statics) {
|
||||
numCallbackParams: 1
|
||||
};
|
||||
|
||||
hooks = hooks.filter(hook => hook.model !== false);
|
||||
hooks = hooks.filter(hook => {
|
||||
// If the custom static overwrites an existing query middleware, don't apply
|
||||
// middleware to it by default. This avoids a potential backwards breaking
|
||||
// change with plugins like `mongoose-delete` that use statics to overwrite
|
||||
// built-in Mongoose functions.
|
||||
if (middlewareFunctions.indexOf(hook.name) !== -1) {
|
||||
return !!hook.model;
|
||||
}
|
||||
return hook.model !== false;
|
||||
});
|
||||
|
||||
model.$__insertMany = hooks.createWrapper('insertMany',
|
||||
model.$__insertMany, model, kareemOptions);
|
||||
@@ -58,4 +68,4 @@ module.exports = function applyStaticHooks(model, hooks, statics) {
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
+26
-10
@@ -38,15 +38,23 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
|
||||
|
||||
const key = model.schema.options.discriminatorKey;
|
||||
|
||||
const baseSchemaAddition = {};
|
||||
baseSchemaAddition[key] = {
|
||||
default: void 0,
|
||||
select: true,
|
||||
$skipDiscriminatorCheck: true
|
||||
};
|
||||
baseSchemaAddition[key][model.schema.options.typeKey] = String;
|
||||
model.schema.add(baseSchemaAddition);
|
||||
defineKey(key, null, model.prototype, null, [key], model.schema.options);
|
||||
const existingPath = model.schema.path(key);
|
||||
if (existingPath != null) {
|
||||
if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) {
|
||||
existingPath.options.select = true;
|
||||
}
|
||||
existingPath.options.$skipDiscriminatorCheck = true;
|
||||
} else {
|
||||
const baseSchemaAddition = {};
|
||||
baseSchemaAddition[key] = {
|
||||
default: void 0,
|
||||
select: true,
|
||||
$skipDiscriminatorCheck: true
|
||||
};
|
||||
baseSchemaAddition[key][model.schema.options.typeKey] = String;
|
||||
model.schema.add(baseSchemaAddition);
|
||||
defineKey(key, null, model.prototype, null, [key], model.schema.options);
|
||||
}
|
||||
|
||||
if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) {
|
||||
throw new Error('Discriminator "' + name +
|
||||
@@ -61,6 +69,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
|
||||
function merge(schema, baseSchema) {
|
||||
// Retain original schema before merging base schema
|
||||
schema._originalSchema = schema.clone();
|
||||
schema._baseSchema = baseSchema;
|
||||
if (baseSchema.paths._id &&
|
||||
baseSchema.paths._id.options &&
|
||||
!baseSchema.paths._id.options.auto) {
|
||||
@@ -94,6 +103,11 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
|
||||
delete schema.paths[conflictingPaths[i]];
|
||||
}
|
||||
|
||||
// Rebuild schema models because schemas may have been merged re: #7884
|
||||
schema.childSchemas.forEach(obj => {
|
||||
obj.model.prototype.$__setSchema(obj.schema);
|
||||
});
|
||||
|
||||
const obj = {};
|
||||
obj[key] = {
|
||||
default: value,
|
||||
@@ -106,7 +120,9 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
|
||||
},
|
||||
$skipDiscriminatorCheck: true
|
||||
};
|
||||
obj[key][schema.options.typeKey] = String;
|
||||
obj[key][schema.options.typeKey] = existingPath ?
|
||||
existingPath.instance :
|
||||
String;
|
||||
schema.add(obj);
|
||||
schema.discriminatorMapping = {key: key, value: value, isRoot: false};
|
||||
|
||||
|
||||
+7
-2
@@ -90,6 +90,11 @@ module.exports = function assignVals(o) {
|
||||
const parts = o.path.split('.');
|
||||
let cur = docs[i];
|
||||
for (let j = 0; j < parts.length - 1; ++j) {
|
||||
// If we get to an array with a dotted path, like `arr.foo`, don't set
|
||||
// `foo` on the array.
|
||||
if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) {
|
||||
break;
|
||||
}
|
||||
if (cur[parts[j]] == null) {
|
||||
cur[parts[j]] = {};
|
||||
}
|
||||
@@ -190,7 +195,7 @@ function valueFilter(val, assignmentOpts, populateOptions) {
|
||||
|
||||
function maybeRemoveId(subdoc, assignmentOpts) {
|
||||
if (assignmentOpts.excludeId) {
|
||||
if (typeof subdoc.setValue === 'function') {
|
||||
if (typeof subdoc.$__setValue === 'function') {
|
||||
delete subdoc._doc._id;
|
||||
} else {
|
||||
delete subdoc._id;
|
||||
@@ -212,4 +217,4 @@ function isPopulatedObject(obj) {
|
||||
obj.$isMongooseMap ||
|
||||
obj.$__ != null ||
|
||||
leanPopulateMap.has(obj);
|
||||
}
|
||||
}
|
||||
|
||||
+6
-4
@@ -9,6 +9,8 @@ const get = require('../get');
|
||||
const leanPopulateMap = require('./leanPopulateMap');
|
||||
const mpath = require('mpath');
|
||||
|
||||
const populateModelSymbol = require('../symbols').populateModelSymbol;
|
||||
|
||||
/*!
|
||||
* @param {Schema} schema
|
||||
* @param {Object} doc POJO
|
||||
@@ -138,18 +140,18 @@ module.exports = function getSchemaTypes(schema, doc, path) {
|
||||
|
||||
const fullPath = nestedPath.concat([trypath]).join('.');
|
||||
if (topLevelDoc.$__ && topLevelDoc.populated(fullPath) && p < parts.length) {
|
||||
const schema = get(doc.$__.populated[fullPath], 'options.model.schema');
|
||||
if (schema != null) {
|
||||
const model = doc.$__.populated[fullPath].options[populateModelSymbol];
|
||||
if (model != null) {
|
||||
const ret = search(
|
||||
parts.slice(p),
|
||||
schema,
|
||||
model.schema,
|
||||
subdoc ? mpath.get(trypath, subdoc) : null,
|
||||
nestedPath.concat(parts.slice(0, p))
|
||||
);
|
||||
|
||||
if (ret) {
|
||||
ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
|
||||
!schema.$isSingleNested;
|
||||
!model.schema.$isSingleNested;
|
||||
}
|
||||
|
||||
return ret;
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ module.exports = function isInclusive(projection) {
|
||||
for (let i = 0; i < numProps; ++i) {
|
||||
const prop = props[i];
|
||||
// Plus paths can't define the projection (see gh-7050)
|
||||
if (prop.charAt(0) === '+') {
|
||||
if (prop.startsWith('+')) {
|
||||
continue;
|
||||
}
|
||||
// If field is truthy (1, true, etc.) and not an object, then this
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
const utils = require('../../utils');
|
||||
|
||||
module.exports = function applyGlobalMaxTimeMS(options, model) {
|
||||
if (utils.hasUserDefinedProperty(options, 'maxTimeMS')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (utils.hasUserDefinedProperty(model.db.options, 'maxTimeMS')) {
|
||||
options.maxTimeMS = model.db.options.maxTimeMS;
|
||||
} else if (utils.hasUserDefinedProperty(model.base.options, 'maxTimeMS')) {
|
||||
options.maxTimeMS = model.base.options.maxTimeMS;
|
||||
}
|
||||
};
|
||||
+3
-3
@@ -3,7 +3,7 @@
|
||||
module.exports = function castFilterPath(query, schematype, val) {
|
||||
const ctx = query;
|
||||
const any$conditionals = Object.keys(val).some(function(k) {
|
||||
return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
|
||||
return k.startsWith('$') && k !== '$id' && k !== '$ref';
|
||||
});
|
||||
|
||||
if (!any$conditionals) {
|
||||
@@ -24,7 +24,7 @@ module.exports = function castFilterPath(query, schematype, val) {
|
||||
if ($cond === '$not') {
|
||||
if (nested && schematype && !schematype.caster) {
|
||||
const _keys = Object.keys(nested);
|
||||
if (_keys.length && _keys[0].charAt(0) === '$') {
|
||||
if (_keys.length && _keys[0].startsWith('$')) {
|
||||
for (const key in nested) {
|
||||
nested[key] = schematype.castForQueryWrapper({
|
||||
$conditional: key,
|
||||
@@ -52,4 +52,4 @@ module.exports = function castFilterPath(query, schematype, val) {
|
||||
}
|
||||
|
||||
return val;
|
||||
};
|
||||
};
|
||||
|
||||
+19
-2
@@ -5,6 +5,7 @@ const StrictModeError = require('../../error/strict');
|
||||
const ValidationError = require('../../error/validation');
|
||||
const castNumber = require('../../cast/number');
|
||||
const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath');
|
||||
const handleImmutable = require('./handleImmutable');
|
||||
const utils = require('../../utils');
|
||||
|
||||
/*!
|
||||
@@ -70,7 +71,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
|
||||
while (i--) {
|
||||
const op = ops[i];
|
||||
val = ret[op];
|
||||
hasDollarKey = hasDollarKey || op.charAt(0) === '$';
|
||||
hasDollarKey = hasDollarKey || op.startsWith('$');
|
||||
|
||||
if (val &&
|
||||
typeof val === 'object' &&
|
||||
@@ -90,6 +91,10 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
|
||||
+ 'Expected an object, received ' + typeof val;
|
||||
throw new Error(msg);
|
||||
}
|
||||
|
||||
if (op.startsWith('$') && Object.keys(val).length === 0) {
|
||||
delete ret[op];
|
||||
}
|
||||
}
|
||||
|
||||
return hasKeys && ret;
|
||||
@@ -137,6 +142,11 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
|
||||
if (val && val.constructor.name === 'Object') {
|
||||
// watch for embedded doc schemas
|
||||
schematype = schema._getSchema(prefix + key);
|
||||
|
||||
if (handleImmutable(schematype, strict, obj, key, prefix + key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (schematype && schematype.caster && op in castOps) {
|
||||
// embedded doc schema
|
||||
if ('$each' in val) {
|
||||
@@ -218,6 +228,13 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
|
||||
const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ?
|
||||
pref : prefix + key;
|
||||
schematype = schema._getSchema(checkPath);
|
||||
|
||||
// You can use `$setOnInsert` with immutable keys
|
||||
if (op !== '$setOnInsert' &&
|
||||
handleImmutable(schematype, strict, obj, key, prefix + key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let pathDetails = schema._getPathType(checkPath);
|
||||
|
||||
// If no schema type, check for embedded discriminators
|
||||
@@ -386,7 +403,7 @@ function castUpdateVal(schema, val, op, $conditional, context, path) {
|
||||
++arrayDepth;
|
||||
}
|
||||
|
||||
let tmp = schema.cast(Array.isArray(val) ? val : [val]);
|
||||
let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context);
|
||||
|
||||
for (let i = 0; i < additionalNesting; ++i) {
|
||||
tmp = tmp[0];
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const StrictModeError = require('../../error/strict');
|
||||
|
||||
module.exports = function handleImmutable(schematype, strict, obj, key, fullPath) {
|
||||
if (schematype == null || !schematype.options.immutable) {
|
||||
return false;
|
||||
}
|
||||
if (strict === false) {
|
||||
return false;
|
||||
}
|
||||
if (strict === 'throw') {
|
||||
throw new StrictModeError(null,
|
||||
`Field ${fullPath} is immutable and strict = 'throw'`);
|
||||
}
|
||||
delete obj[key];
|
||||
return true;
|
||||
};
|
||||
+1
-1
@@ -8,7 +8,7 @@ module.exports = function(obj) {
|
||||
const keys = Object.keys(obj);
|
||||
const len = keys.length;
|
||||
for (let i = 0; i < len; ++i) {
|
||||
if (keys[i].charAt(0) === '$') {
|
||||
if (keys[i].startsWith('$')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+9
-7
@@ -15,13 +15,15 @@ module.exports = function applyPlugins(schema, plugins, options, cacheKey) {
|
||||
options = Object.assign({}, options);
|
||||
delete options.skipTopLevel;
|
||||
|
||||
for (const path of Object.keys(schema.paths)) {
|
||||
const type = schema.paths[path];
|
||||
if (type.schema != null) {
|
||||
applyPlugins(type.schema, plugins, options, cacheKey);
|
||||
if (options.applyPluginsToChildSchemas !== false) {
|
||||
for (const path of Object.keys(schema.paths)) {
|
||||
const type = schema.paths[path];
|
||||
if (type.schema != null) {
|
||||
applyPlugins(type.schema, plugins, options, cacheKey);
|
||||
|
||||
// Recompile schema because plugins may have changed it, see gh-7572
|
||||
type.caster.prototype.$__setSchema(type.schema);
|
||||
// Recompile schema because plugins may have changed it, see gh-7572
|
||||
type.caster.prototype.$__setSchema(type.schema);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,4 +42,4 @@ module.exports = function applyPlugins(schema, plugins, options, cacheKey) {
|
||||
applyPlugins(discriminatorSchema, plugins,
|
||||
{ skipTopLevel: !applyPluginsToDiscriminators }, cacheKey);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function merge(s1, s2) {
|
||||
s1.add(s2.obj);
|
||||
s1.add(s2.obj || {});
|
||||
|
||||
s1.callQueue = s1.callQueue.concat(s2.callQueue);
|
||||
s1.method(s2.methods);
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
module.exports = function(schematype) {
|
||||
if (schematype.$immutable) {
|
||||
schematype.$immutableSetter = createImmutableSetter(schematype.path);
|
||||
schematype.set(schematype.$immutableSetter);
|
||||
} else if (schematype.$immutableSetter) {
|
||||
schematype.setters = schematype.setters.
|
||||
filter(fn => fn !== schematype.$immutableSetter);
|
||||
delete schematype.$immutableSetter;
|
||||
}
|
||||
};
|
||||
|
||||
function createImmutableSetter(path) {
|
||||
return function immutableSetter(v) {
|
||||
if (this.$__ == null) {
|
||||
return v;
|
||||
}
|
||||
if (this.isNew) {
|
||||
return v;
|
||||
}
|
||||
return this[path];
|
||||
};
|
||||
}
|
||||
+6
-3
@@ -29,7 +29,7 @@ module.exports = function(filter, schema, castedDoc, options) {
|
||||
}
|
||||
|
||||
for (let i = 0; i < numKeys; ++i) {
|
||||
if (keys[i].charAt(0) === '$') {
|
||||
if (keys[i].startsWith('$')) {
|
||||
modifiedPaths(castedDoc[keys[i]], '', modified);
|
||||
hasDollarUpdate = true;
|
||||
}
|
||||
@@ -49,7 +49,7 @@ module.exports = function(filter, schema, castedDoc, options) {
|
||||
const numConditionKeys = conditionKeys.length;
|
||||
let hasDollarKey = false;
|
||||
for (let j = 0; j < numConditionKeys; ++j) {
|
||||
if (conditionKeys[j].charAt(0) === '$') {
|
||||
if (conditionKeys[j].startsWith('$')) {
|
||||
hasDollarKey = true;
|
||||
break;
|
||||
}
|
||||
@@ -69,7 +69,10 @@ module.exports = function(filter, schema, castedDoc, options) {
|
||||
}
|
||||
|
||||
schema.eachPath(function(path, schemaType) {
|
||||
if (schemaType.$isSingleNested) {
|
||||
// Skip single nested paths if underneath a map
|
||||
const isUnderneathMap = schemaType.path.endsWith('.$*') ||
|
||||
schemaType.path.indexOf('.$*.') !== -1;
|
||||
if (schemaType.$isSingleNested && !isUnderneathMap) {
|
||||
// Only handle nested schemas 1-level deep to avoid infinite
|
||||
// recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11
|
||||
schemaType.schema.eachPath(function(_path, _schemaType) {
|
||||
|
||||
+3
-1
@@ -5,8 +5,10 @@ exports.arrayParentSymbol = Symbol('mongoose#Array#_parent');
|
||||
exports.arrayPathSymbol = Symbol('mongoose#Array#_path');
|
||||
exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema');
|
||||
exports.documentArrayParent = Symbol('mongoose:documentArrayParent');
|
||||
exports.documentSchemaSymbol = Symbol('mongoose#Document#schema');
|
||||
exports.getSymbol = Symbol('mongoose#Document#get');
|
||||
exports.modelSymbol = Symbol('mongoose#Model');
|
||||
exports.objectIdSymbol = Symbol('mongoose#ObjectId');
|
||||
exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model');
|
||||
exports.schemaTypeSymbol = Symbol('mongoose#schemaType');
|
||||
exports.validatorErrorSymbol = Symbol('mongoose:validatorError');
|
||||
exports.validatorErrorSymbol = Symbol('mongoose:validatorError');
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ function applyTimestampsToChildren(now, update, schema) {
|
||||
let timestamps;
|
||||
let path;
|
||||
|
||||
const hasDollarKey = keys.length && keys[0].charAt(0) === '$';
|
||||
const hasDollarKey = keys.length && keys[0].startsWith('$');
|
||||
|
||||
if (hasDollarKey) {
|
||||
if (update.$push) {
|
||||
@@ -173,4 +173,4 @@ function applyTimestampsToSingleNested(subdoc, schematype, now) {
|
||||
if (createdAt != null) {
|
||||
subdoc[createdAt] = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -38,7 +38,7 @@ module.exports = function(query, schema, castedDoc, options) {
|
||||
let i;
|
||||
|
||||
for (i = 0; i < numKeys; ++i) {
|
||||
if (keys[i].charAt(0) === '$') {
|
||||
if (keys[i].startsWith('$')) {
|
||||
hasDollarUpdate = true;
|
||||
if (keys[i] === '$push' || keys[i] === '$addToSet') {
|
||||
_keys = Object.keys(castedDoc[keys[i]]);
|
||||
@@ -63,7 +63,7 @@ module.exports = function(query, schema, castedDoc, options) {
|
||||
key = keys[i];
|
||||
// With `$pull` we might flatten `$in`. Skip stuff nested under `$in`
|
||||
// for the rest of the logic, it will get handled later.
|
||||
if (updatedPath.indexOf('$') !== -1) {
|
||||
if (updatedPath.includes('$')) {
|
||||
continue;
|
||||
}
|
||||
if (key === '$set' || key === '$setOnInsert' ||
|
||||
|
||||
+7
-1
@@ -140,12 +140,14 @@ Mongoose.prototype.driver = require('./driver');
|
||||
* - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default
|
||||
* - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model.
|
||||
* - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
|
||||
* - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas
|
||||
* - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter.
|
||||
* - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default.
|
||||
* - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject)
|
||||
* - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()`
|
||||
* - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas.
|
||||
* - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
|
||||
* - 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query
|
||||
*
|
||||
* @param {String} key
|
||||
* @param {String|Function|Boolean} value
|
||||
@@ -286,6 +288,9 @@ Mongoose.prototype.createConnection = function(uri, options, callback) {
|
||||
Mongoose.prototype.connect = function() {
|
||||
const _mongoose = this instanceof Mongoose ? this : mongoose;
|
||||
const conn = _mongoose.connection;
|
||||
if (conn.readyState !== STATES.disconnected) {
|
||||
throw new _mongoose.Error('You can not `mongoose.connect()` multiple times while connected.');
|
||||
}
|
||||
return conn.openUri(arguments[0], arguments[1], arguments[2]).then(() => _mongoose);
|
||||
};
|
||||
|
||||
@@ -406,7 +411,6 @@ Mongoose.prototype.pluralize = function(fn) {
|
||||
|
||||
Mongoose.prototype.model = function(name, schema, collection, skipInit) {
|
||||
const _mongoose = this instanceof Mongoose ? this : mongoose;
|
||||
|
||||
let model;
|
||||
if (typeof name === 'function') {
|
||||
model = name;
|
||||
@@ -574,6 +578,8 @@ Mongoose.prototype._applyPlugins = function(schema, options) {
|
||||
options = options || {};
|
||||
options.applyPluginsToDiscriminators = get(this,
|
||||
'options.applyPluginsToDiscriminators', false);
|
||||
options.applyPluginsToChildSchemas = get(this,
|
||||
'options.applyPluginsToChildSchemas', true);
|
||||
applyPlugins(schema, this.plugins, options, '$globalPluginsApplied');
|
||||
};
|
||||
|
||||
|
||||
+185
-51
@@ -52,6 +52,7 @@ const VERSION_ALL = VERSION_WHERE | VERSION_INC;
|
||||
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
|
||||
const modelCollectionSymbol = Symbol.for('mongoose#Model#collection');
|
||||
const modelSymbol = require('./helpers/symbols').modelSymbol;
|
||||
const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
|
||||
const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
|
||||
const subclassedSymbol = Symbol('mongoose#Model#subclassed');
|
||||
|
||||
@@ -78,7 +79,7 @@ const subclassedSymbol = Symbol('mongoose#Model#subclassed');
|
||||
* const userFromDb = await UserModel.findOne({ name: 'Foo' });
|
||||
*
|
||||
* @param {Object} doc values for initial set
|
||||
* @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projetion](./api.html#query_Query-select).
|
||||
* @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select).
|
||||
* @inherits Document http://mongoosejs.com/docs/api.html#document-js
|
||||
* @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
|
||||
* @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
|
||||
@@ -326,9 +327,10 @@ Model.prototype.$__handleSave = function(options, callback) {
|
||||
|
||||
Model.prototype.$__save = function(options, callback) {
|
||||
this.$__handleSave(options, (error, result) => {
|
||||
const hooks = this.schema.s.hooks;
|
||||
if (error) {
|
||||
return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) {
|
||||
callback(error);
|
||||
return hooks.execPost('save:error', this, [this], { error: error }, (error) => {
|
||||
callback(error, this);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -359,7 +361,7 @@ Model.prototype.$__save = function(options, callback) {
|
||||
this.$__.version = undefined;
|
||||
|
||||
const key = this.schema.options.versionKey;
|
||||
const version = this.getValue(key) || 0;
|
||||
const version = this.$__getValue(key) || 0;
|
||||
|
||||
if (numAffected <= 0) {
|
||||
// the update failed. pass an error back
|
||||
@@ -370,14 +372,15 @@ Model.prototype.$__save = function(options, callback) {
|
||||
|
||||
// increment version if was successful
|
||||
if (doIncrement) {
|
||||
this.setValue(key, version + 1);
|
||||
this.$__setValue(key, version + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (result != null && numAffected <= 0) {
|
||||
error = new DocumentNotFoundError(result.$where);
|
||||
return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) {
|
||||
callback(error);
|
||||
error = new DocumentNotFoundError(result.$where,
|
||||
this.constructor.modelName, numAffected, result);
|
||||
return hooks.execPost('save:error', this, [this], { error: error }, (error) => {
|
||||
callback(error, this);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -397,7 +400,7 @@ function generateVersionError(doc, modifiedPaths) {
|
||||
if (!key) {
|
||||
return null;
|
||||
}
|
||||
const version = doc.getValue(key) || 0;
|
||||
const version = doc.$__getValue(key) || 0;
|
||||
return new VersionError(doc, version, modifiedPaths);
|
||||
}
|
||||
|
||||
@@ -785,7 +788,7 @@ Model.prototype.$__version = function(where, delta) {
|
||||
|
||||
if (where === true) {
|
||||
// this is an insert
|
||||
if (key) this.setValue(key, delta[key] = 0);
|
||||
if (key) this.$__setValue(key, delta[key] = 0);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -801,7 +804,7 @@ Model.prototype.$__version = function(where, delta) {
|
||||
|
||||
// $push $addToSet don't need the where clause set
|
||||
if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
|
||||
const value = this.getValue(key);
|
||||
const value = this.$__getValue(key);
|
||||
if (value != null) where[key] = value;
|
||||
}
|
||||
|
||||
@@ -998,6 +1001,45 @@ Model.prototype.model = function model(name) {
|
||||
return this.db.model(name);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if at least one document exists in the database that matches
|
||||
* the given `filter`, and false otherwise.
|
||||
*
|
||||
* Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to
|
||||
* `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)`
|
||||
*
|
||||
* ####Example:
|
||||
* await Character.deleteMany({});
|
||||
* await Character.create({ name: 'Jean-Luc Picard' });
|
||||
*
|
||||
* await Character.exists({ name: /picard/i }); // true
|
||||
* await Character.exists({ name: /riker/i }); // false
|
||||
*
|
||||
* This function triggers the following middleware.
|
||||
*
|
||||
* - `findOne()`
|
||||
*
|
||||
* @param {Object} filter
|
||||
* @param {Function} [callback] callback
|
||||
* @return {Promise}
|
||||
*/
|
||||
|
||||
Model.exists = function exists(filter, callback) {
|
||||
const query = this.findOne(filter).select({ _id: 1 }).lean();
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
query.exec(function(err, doc) {
|
||||
if (err != null) {
|
||||
return callback(err);
|
||||
}
|
||||
callback(null, !!doc);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
return query.then(doc => !!doc);
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a discriminator type.
|
||||
*
|
||||
@@ -1471,6 +1513,9 @@ function _ensureIndexes(model, options, callback) {
|
||||
model.emit('index-single-start', fields, options);
|
||||
};
|
||||
|
||||
const baseSchema = model.schema._baseSchema;
|
||||
const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : [];
|
||||
|
||||
const create = function() {
|
||||
if (options._automatic) {
|
||||
if (model.schema.options.autoIndex === false ||
|
||||
@@ -1484,6 +1529,10 @@ function _ensureIndexes(model, options, callback) {
|
||||
return done();
|
||||
}
|
||||
|
||||
if (baseSchemaIndexes.find(i => utils.deepEqual(i, index))) {
|
||||
return create();
|
||||
}
|
||||
|
||||
const indexFields = utils.clone(index[0]);
|
||||
const indexOptions = utils.clone(index[1]);
|
||||
|
||||
@@ -1751,21 +1800,30 @@ Model.remove = function remove(conditions, callback) {
|
||||
* Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks.
|
||||
*
|
||||
* @param {Object} conditions
|
||||
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
||||
* @param {Function} [callback]
|
||||
* @return {Query}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Model.deleteOne = function deleteOne(conditions, callback) {
|
||||
Model.deleteOne = function deleteOne(conditions, options, callback) {
|
||||
if (typeof conditions === 'function') {
|
||||
callback = conditions;
|
||||
conditions = {};
|
||||
options = null;
|
||||
}
|
||||
else if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = null;
|
||||
}
|
||||
|
||||
// get the mongodb collection object
|
||||
const mq = new this.Query(conditions, {}, this, this.collection);
|
||||
mq.setOptions(options);
|
||||
|
||||
callback = this.$wrapCallback(callback);
|
||||
if (callback) {
|
||||
callback = this.$wrapCallback(callback);
|
||||
}
|
||||
|
||||
return mq.deleteOne(callback);
|
||||
};
|
||||
@@ -2284,6 +2342,7 @@ Model.$where = function $where() {
|
||||
* @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
||||
* @param {Function} [callback]
|
||||
* @return {Query}
|
||||
* @see Tutorial /docs/tutorials/findoneandupdate.html
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
|
||||
* @api public
|
||||
*/
|
||||
@@ -3112,6 +3171,7 @@ Model.$__insertMany = function(arr, options, callback) {
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < docAttributes.length; ++i) {
|
||||
docAttributes[i].$__reset();
|
||||
docAttributes[i].isNew = false;
|
||||
docAttributes[i].emit('isNew', false);
|
||||
docAttributes[i].constructor.emit('isNew', false);
|
||||
@@ -3282,13 +3342,15 @@ Model.hydrate = function(obj) {
|
||||
*
|
||||
* ####Valid options:
|
||||
*
|
||||
* - `safe` (boolean) safe mode (defaults to value set in schema (true))
|
||||
* - `upsert` (boolean) whether to create the doc if it doesn't match (false)
|
||||
* - `multi` (boolean) whether multiple documents should be updated (false)
|
||||
* - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update
|
||||
* - `upsert` (boolean): whether to create the doc if it doesn't match (false)
|
||||
* - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
|
||||
* - `omitUndefined` (boolean): If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
||||
* - `multi` (boolean): whether multiple documents should be updated (false)
|
||||
* - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
|
||||
* - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
|
||||
* - `strict` (boolean) overrides the `strict` option for this update
|
||||
* - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
|
||||
* - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
|
||||
* - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
|
||||
* - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false)
|
||||
*
|
||||
* All `update` values are cast to their appropriate SchemaTypes before being sent.
|
||||
*
|
||||
@@ -3318,14 +3380,15 @@ Model.hydrate = function(obj) {
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* Although values are casted to their appropriate types when using update, the following are *not* applied:
|
||||
* Mongoose casts values and runs setters when using update. The following
|
||||
* features are **not** applied by default.
|
||||
*
|
||||
* - defaults
|
||||
* - setters
|
||||
* - validators
|
||||
* - [defaults](/docs/defaults.html#the-setdefaultsoninsert-option)
|
||||
* - [validators](/docs/validation.html#update-validators)
|
||||
* - middleware
|
||||
*
|
||||
* If you need those features, use the traditional approach of first retrieving the document.
|
||||
* If you need document middleware and fully-featured validation, load the
|
||||
* document first and then use [`save()`](/docs/api.html#model_Model-save).
|
||||
*
|
||||
* Model.findOne({ name: 'borne' }, function (err, doc) {
|
||||
* if (err) ..
|
||||
@@ -3335,14 +3398,18 @@ Model.hydrate = function(obj) {
|
||||
*
|
||||
* @see strict http://mongoosejs.com/docs/guide.html#strict
|
||||
* @see response http://docs.mongodb.org/v2.6/reference/command/update/#output
|
||||
* @param {Object} conditions
|
||||
* @param {Object} filter
|
||||
* @param {Object} doc
|
||||
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
||||
* @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
||||
* @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
|
||||
* @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
|
||||
* @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
||||
* @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`.
|
||||
* @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
|
||||
* @param {Boolean} [options.setDefaultsOnInsert=false] if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
|
||||
* @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
|
||||
* @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`.
|
||||
* @param {Function} [callback] params are (error, writeOpResult)
|
||||
* @param {Function} [callback]
|
||||
* @return {Query}
|
||||
@@ -3358,7 +3425,7 @@ Model.update = function update(conditions, doc, options, callback) {
|
||||
|
||||
/**
|
||||
* Same as `update()`, except MongoDB will update _all_ documents that match
|
||||
* `criteria` (as opposed to just the first one) regardless of the value of
|
||||
* `filter` (as opposed to just the first one) regardless of the value of
|
||||
* the `multi` option.
|
||||
*
|
||||
* **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
|
||||
@@ -3373,7 +3440,7 @@ Model.update = function update(conditions, doc, options, callback) {
|
||||
*
|
||||
* - `updateMany()`
|
||||
*
|
||||
* @param {Object} conditions
|
||||
* @param {Object} filter
|
||||
* @param {Object} doc
|
||||
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
||||
* @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
||||
@@ -3397,7 +3464,7 @@ Model.updateMany = function updateMany(conditions, doc, options, callback) {
|
||||
* Same as `update()`, except it does not support the `multi` or `overwrite`
|
||||
* options.
|
||||
*
|
||||
* - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option.
|
||||
* - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option.
|
||||
* - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`.
|
||||
*
|
||||
* ####Example:
|
||||
@@ -3409,7 +3476,7 @@ Model.updateMany = function updateMany(conditions, doc, options, callback) {
|
||||
*
|
||||
* - `updateOne()`
|
||||
*
|
||||
* @param {Object} conditions
|
||||
* @param {Object} filter
|
||||
* @param {Object} doc
|
||||
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
||||
* @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
||||
@@ -3442,7 +3509,7 @@ Model.updateOne = function updateOne(conditions, doc, options, callback) {
|
||||
*
|
||||
* - `replaceOne()`
|
||||
*
|
||||
* @param {Object} conditions
|
||||
* @param {Object} filter
|
||||
* @param {Object} doc
|
||||
* @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
|
||||
* @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
|
||||
@@ -3836,6 +3903,7 @@ Model.geoSearch = function(conditions, options, callback) {
|
||||
* @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options).
|
||||
* @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
|
||||
* @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object.
|
||||
* @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type.
|
||||
* @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
|
||||
* @return {Promise}
|
||||
* @api public
|
||||
@@ -3870,18 +3938,16 @@ Model.populate = function(docs, paths, callback) {
|
||||
*/
|
||||
|
||||
function _populate(model, docs, paths, cache, callback) {
|
||||
const length = paths.length;
|
||||
let pending = paths.length;
|
||||
|
||||
if (pending === 0) {
|
||||
if (length === 0) {
|
||||
return callback(null, docs);
|
||||
}
|
||||
|
||||
// each path has its own query options and must be executed separately
|
||||
let i = pending;
|
||||
let path;
|
||||
while (i--) {
|
||||
path = paths[i];
|
||||
populate(model, docs, path, next);
|
||||
for (let i = 0; i < length; ++i) {
|
||||
populate(model, docs, paths[i], next);
|
||||
}
|
||||
|
||||
function next(err) {
|
||||
@@ -3957,7 +4023,9 @@ function populate(model, docs, options, callback) {
|
||||
hasOne = true;
|
||||
if (mod.foreignField.size === 1) {
|
||||
const foreignField = Array.from(mod.foreignField)[0];
|
||||
const foreignSchemaType = mod.model.schema.path(foreignField);
|
||||
if (foreignField !== '_id' || !match['_id']) {
|
||||
ids = _filterInvalidIds(ids, foreignSchemaType, mod.options.skipInvalidIds);
|
||||
match[foreignField] = { $in: ids };
|
||||
}
|
||||
} else {
|
||||
@@ -3970,6 +4038,8 @@ function populate(model, docs, options, callback) {
|
||||
}
|
||||
for (const foreignField of mod.foreignField) {
|
||||
if (foreignField !== '_id' || !match['_id']) {
|
||||
const foreignSchemaType = mod.model.schema.path(foreignField);
|
||||
ids = _filterInvalidIds(ids, foreignSchemaType, mod.options.skipInvalidIds);
|
||||
$or.push({ [foreignField]: { $in: ids } });
|
||||
}
|
||||
}
|
||||
@@ -4146,6 +4216,25 @@ function populate(model, docs, options, callback) {
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* Optionally filter out invalid ids that don't conform to foreign field's schema
|
||||
* to avoid cast errors (gh-7706)
|
||||
*/
|
||||
|
||||
function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) {
|
||||
if (!skipInvalidIds) {
|
||||
return ids;
|
||||
}
|
||||
return ids.filter(id => {
|
||||
try {
|
||||
foreignSchemaType.cast(id);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/*!
|
||||
* Format `mod.match` given that it may be an array that we need to $or if
|
||||
* the client has multiple docs with match functions
|
||||
@@ -4174,7 +4263,6 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
let currentOptions;
|
||||
let modelNames;
|
||||
let modelName;
|
||||
let discriminatorKey;
|
||||
let modelForFindSchema;
|
||||
|
||||
const originalModel = options.model;
|
||||
@@ -4252,6 +4340,13 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
let justOne = null;
|
||||
if ('justOne' in options) {
|
||||
justOne = options.justOne;
|
||||
} else if (virtual && virtual.options && virtual.options.refPath) {
|
||||
const normalizedRefPath =
|
||||
normalizeRefPath(virtual.options.refPath, doc, options.path);
|
||||
justOne = !!virtual.options.justOne;
|
||||
isVirtual = true;
|
||||
const refValue = utils.getValue(normalizedRefPath, doc);
|
||||
modelNames = Array.isArray(refValue) ? refValue : [refValue];
|
||||
} else if (virtual && virtual.options && virtual.options.ref) {
|
||||
let normalizedRef;
|
||||
if (typeof virtual.options.ref === 'function') {
|
||||
@@ -4330,10 +4425,14 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// `PopulateOptions#connection`: if the model is passed as a string, the
|
||||
// connection matters because different connections have different models.
|
||||
const connection = options.connection != null ? options.connection : model.db;
|
||||
|
||||
try {
|
||||
Model = originalModel && originalModel[modelSymbol] ?
|
||||
originalModel :
|
||||
modelName[modelSymbol] ? modelName : model.db.model(modelName);
|
||||
modelName[modelSymbol] ? modelName : connection.model(modelName);
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
@@ -4353,10 +4452,10 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
currentOptions.options = utils.clone(virtual.options.options);
|
||||
}
|
||||
utils.merge(currentOptions, options);
|
||||
if (schema && !discriminatorKey) {
|
||||
currentOptions.model = Model;
|
||||
}
|
||||
options.model = Model;
|
||||
|
||||
// Used internally for checking what model was used to populate this
|
||||
// path.
|
||||
options[populateModelSymbol] = Model;
|
||||
|
||||
available[modelName] = {
|
||||
model: Model,
|
||||
@@ -4370,7 +4469,8 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
justOne: justOne,
|
||||
isVirtual: isVirtual,
|
||||
virtual: virtual,
|
||||
count: count
|
||||
count: count,
|
||||
[populateModelSymbol]: Model
|
||||
};
|
||||
map.push(available[modelName]);
|
||||
} else {
|
||||
@@ -4447,11 +4547,10 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
|
||||
let ref;
|
||||
if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) {
|
||||
ref = handleRefFunction(ref, doc);
|
||||
modelNames = [ref];
|
||||
} else if ((ref = get(virtual, 'options.ref')) != null) {
|
||||
if (typeof ref === 'function') {
|
||||
ref = ref.call(doc, doc);
|
||||
}
|
||||
ref = handleRefFunction(ref, doc);
|
||||
|
||||
// When referencing nested arrays, the ref should be an Array
|
||||
// of modelNames.
|
||||
@@ -4483,6 +4582,17 @@ function getModelsMapForPopulate(model, docs, options) {
|
||||
return map;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function handleRefFunction(ref, doc) {
|
||||
if (typeof ref === 'function' && !ref[modelSymbol]) {
|
||||
return ref.call(doc, doc);
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Retrieve the _id of `val` if a Document or Array of Documents.
|
||||
*
|
||||
@@ -4559,12 +4669,16 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
|
||||
}
|
||||
const discriminatorKey = model.schema.options.discriminatorKey;
|
||||
|
||||
if (model.discriminators == null || doc == null || doc[discriminatorKey] == null) {
|
||||
Model.call(this, doc, fields, skipId);
|
||||
return;
|
||||
}
|
||||
|
||||
// If discriminator key is set, use the discriminator instead (gh-7586)
|
||||
if (model.discriminators != null &&
|
||||
doc != null &&
|
||||
doc[discriminatorKey] != null &&
|
||||
model.discriminators[doc[discriminatorKey]] != null) {
|
||||
return new model.discriminators[doc[discriminatorKey]](doc, fields, skipId);
|
||||
const Discriminator = model.discriminators[doc[discriminatorKey]] ||
|
||||
getDiscriminatorByValue(model, doc[discriminatorKey]);
|
||||
if (Discriminator != null) {
|
||||
return new Discriminator(doc, fields, skipId);
|
||||
}
|
||||
|
||||
// Otherwise, just use the top-level model
|
||||
@@ -4736,6 +4850,26 @@ Model.$wrapCallback = function(callback) {
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper for console.log
|
||||
*
|
||||
* @api public
|
||||
* @method inspect
|
||||
* @instance
|
||||
*/
|
||||
|
||||
Model.inspect = function() {
|
||||
return `Model { ${this.modelName} }`;
|
||||
};
|
||||
|
||||
if (util.inspect.custom) {
|
||||
/*!
|
||||
* Avoid Node deprecation warning DEP0079
|
||||
*/
|
||||
|
||||
Model[util.inspect.custom] = Model.inspect;
|
||||
}
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
const utils = require('../utils');
|
||||
|
||||
class PopulateOptions {
|
||||
constructor(obj) {
|
||||
this._docs = {};
|
||||
|
||||
if (obj == null) {
|
||||
return;
|
||||
}
|
||||
obj = utils.clone(obj);
|
||||
Object.assign(this, obj);
|
||||
if (typeof obj.subPopulate === 'object') {
|
||||
this.populate = obj.subPopulate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection used to look up models by name. If not specified, Mongoose
|
||||
* will default to using the connection associated with the model in
|
||||
* `PopulateOptions#model`.
|
||||
*
|
||||
* @memberOf PopulateOptions
|
||||
* @property {Connection} connection
|
||||
* @api public
|
||||
*/
|
||||
|
||||
module.exports = PopulateOptions;
|
||||
+1
-1
@@ -67,7 +67,7 @@ function storeShard() {
|
||||
let val;
|
||||
|
||||
for (let i = 0; i < len; ++i) {
|
||||
val = this.getValue(paths[i]);
|
||||
val = this.$__getValue(paths[i]);
|
||||
if (val == null) {
|
||||
orig[paths[i]] = val;
|
||||
} else if (utils.isMongooseObject(val)) {
|
||||
|
||||
+78
-22
@@ -11,6 +11,7 @@ const MongooseError = require('./error/mongooseError');
|
||||
const ObjectParameterError = require('./error/objectParameter');
|
||||
const QueryCursor = require('./cursor/QueryCursor');
|
||||
const ReadPreference = require('./driver').get().ReadPreference;
|
||||
const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS');
|
||||
const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
|
||||
const cast = require('./cast');
|
||||
const castArrayFilters = require('./helpers/update/castArrayFilters');
|
||||
@@ -643,7 +644,7 @@ Query.prototype.mod = function() {
|
||||
* @memberOf Query
|
||||
* @instance
|
||||
* @param {String|Object|Function} path
|
||||
* @param {Object|Function} criteria
|
||||
* @param {Object|Function} filter
|
||||
* @return {Query} this
|
||||
* @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/
|
||||
* @api public
|
||||
@@ -1411,7 +1412,27 @@ Query.prototype.maxTimeMS = function(ms) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the current query conditions as a JSON object.
|
||||
* Returns the current query filter (also known as conditions) as a POJO.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* const query = new Query();
|
||||
* query.find({ a: 1 }).where('b').gt(2);
|
||||
* query.getFilter(); // { a: 1, b: { $gt: 2 } }
|
||||
*
|
||||
* @return {Object} current query filter
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Query.prototype.getFilter = function() {
|
||||
return this._conditions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the current query filter. Equivalent to `getFilter()`.
|
||||
*
|
||||
* You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()`
|
||||
* will likely be deprecated in a future release.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
@@ -1419,7 +1440,7 @@ Query.prototype.maxTimeMS = function(ms) {
|
||||
* query.find({ a: 1 }).where('b').gt(2);
|
||||
* query.getQuery(); // { a: 1, b: { $gt: 2 } }
|
||||
*
|
||||
* @return {Object} current query conditions
|
||||
* @return {Object} current query filter
|
||||
* @api public
|
||||
*/
|
||||
|
||||
@@ -1803,6 +1824,8 @@ Query.prototype._find = wrapThunk(function(callback) {
|
||||
const _this = this;
|
||||
const userProvidedFields = _this._userProvidedFields || {};
|
||||
|
||||
applyGlobalMaxTimeMS(this.options, this.model);
|
||||
|
||||
// Separate options to pass down to `completeMany()` in case we need to
|
||||
// set a session on the document
|
||||
const completeManyOptions = Object.assign({}, {
|
||||
@@ -2022,6 +2045,8 @@ Query.prototype._findOne = wrapThunk(function(callback) {
|
||||
this._applyPaths();
|
||||
this._fields = this._castFields(this._fields);
|
||||
|
||||
applyGlobalMaxTimeMS(this.options, this.model);
|
||||
|
||||
// don't pass in the conditions because we already merged them in
|
||||
Query.base.findOne.call(this, {}, (err, doc) => {
|
||||
if (err) {
|
||||
@@ -2629,7 +2654,7 @@ Query.prototype._deleteOne = wrapThunk(function(callback) {
|
||||
|
||||
/**
|
||||
* Declare and/or execute this query as a `deleteMany()` operation. Works like
|
||||
* remove, except it deletes _every_ document that matches `criteria` in the
|
||||
* remove, except it deletes _every_ document that matches `filter` in the
|
||||
* collection, regardless of the value of `single`.
|
||||
*
|
||||
* This function does not trigger any middleware
|
||||
@@ -2811,7 +2836,7 @@ function prepareDiscriminatorCriteria(query) {
|
||||
* @method findOneAndUpdate
|
||||
* @memberOf Query
|
||||
* @instance
|
||||
* @param {Object|Query} [query]
|
||||
* @param {Object|Query} [filter]
|
||||
* @param {Object} [doc]
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
|
||||
@@ -2820,6 +2845,7 @@ function prepareDiscriminatorCriteria(query) {
|
||||
* @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
|
||||
* @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
|
||||
* @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult)
|
||||
* @see Tutorial /docs/tutorials/findoneandupdate.html
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
|
||||
* @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
|
||||
* @return {Query} this
|
||||
@@ -3181,6 +3207,9 @@ Query.prototype.findOneAndReplace = function(filter, replacement, options, callb
|
||||
}
|
||||
|
||||
if (replacement != null) {
|
||||
if (hasDollarKeys(replacement)) {
|
||||
throw new Error('The replacement document must not contain atomic operators.');
|
||||
}
|
||||
this._mergeUpdate(replacement);
|
||||
}
|
||||
|
||||
@@ -3214,6 +3243,9 @@ Query.prototype._findOneAndReplace = wrapThunk(function(callback) {
|
||||
const options = this._optionsForExec();
|
||||
let fields = null;
|
||||
|
||||
let castedDoc = new this.model(this._update, null, true);
|
||||
|
||||
this._applyPaths();
|
||||
if (this._fields != null) {
|
||||
options.projection = this._castFields(utils.clone(this._fields));
|
||||
fields = options.projection;
|
||||
@@ -3223,14 +3255,24 @@ Query.prototype._findOneAndReplace = wrapThunk(function(callback) {
|
||||
}
|
||||
}
|
||||
|
||||
this._collection.collection.findOneAndReplace(filter, options, (err, res) => {
|
||||
if (err) {
|
||||
castedDoc.validate(err => {
|
||||
if (err != null) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
const doc = res.value;
|
||||
if (castedDoc.toBSON) {
|
||||
castedDoc = castedDoc.toBSON();
|
||||
}
|
||||
|
||||
return this._completeOne(doc, res, callback);
|
||||
this._collection.collection.findOneAndReplace(filter, castedDoc, options, (err, res) => {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
const doc = res.value;
|
||||
|
||||
return this._completeOne(doc, res, callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3733,17 +3775,17 @@ Query.prototype._replaceOne = wrapThunk(function(callback) {
|
||||
*
|
||||
* API summary
|
||||
*
|
||||
* update(criteria, doc, options, cb) // executes
|
||||
* update(criteria, doc, options)
|
||||
* update(criteria, doc, cb) // executes
|
||||
* update(criteria, doc)
|
||||
* update(filter, doc, options, cb) // executes
|
||||
* update(filter, doc, options)
|
||||
* update(filter, doc, cb) // executes
|
||||
* update(filter, doc)
|
||||
* update(doc, cb) // executes
|
||||
* update(doc)
|
||||
* update(cb) // executes
|
||||
* update(true) // executes
|
||||
* update()
|
||||
*
|
||||
* @param {Object} [criteria]
|
||||
* @param {Object} [filter]
|
||||
* @param {Object} [doc] the update command
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
||||
@@ -3794,7 +3836,7 @@ Query.prototype.update = function(conditions, doc, options, callback) {
|
||||
/**
|
||||
* Declare and/or execute this query as an updateMany() operation. Same as
|
||||
* `update()`, except MongoDB will update _all_ documents that match
|
||||
* `criteria` (as opposed to just the first one) regardless of the value of
|
||||
* `filter` (as opposed to just the first one) regardless of the value of
|
||||
* the `multi` option.
|
||||
*
|
||||
* **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
|
||||
@@ -3809,7 +3851,7 @@ Query.prototype.update = function(conditions, doc, options, callback) {
|
||||
*
|
||||
* - `updateMany()`
|
||||
*
|
||||
* @param {Object} [criteria]
|
||||
* @param {Object} [filter]
|
||||
* @param {Object} [doc] the update command
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
||||
@@ -3861,7 +3903,7 @@ Query.prototype.updateMany = function(conditions, doc, options, callback) {
|
||||
* Declare and/or execute this query as an updateOne() operation. Same as
|
||||
* `update()`, except it does not support the `multi` or `overwrite` options.
|
||||
*
|
||||
* - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option.
|
||||
* - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option.
|
||||
* - Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`.
|
||||
*
|
||||
* **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')`
|
||||
@@ -3876,7 +3918,7 @@ Query.prototype.updateMany = function(conditions, doc, options, callback) {
|
||||
*
|
||||
* - `updateOne()`
|
||||
*
|
||||
* @param {Object} [criteria]
|
||||
* @param {Object} [filter]
|
||||
* @param {Object} [doc] the update command
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
||||
@@ -3941,7 +3983,7 @@ Query.prototype.updateOne = function(conditions, doc, options, callback) {
|
||||
*
|
||||
* - `replaceOne()`
|
||||
*
|
||||
* @param {Object} [criteria]
|
||||
* @param {Object} [filter]
|
||||
* @param {Object} [doc] the update command
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
|
||||
@@ -4156,7 +4198,7 @@ function _orFailError(err, query) {
|
||||
}
|
||||
|
||||
if (err == null) {
|
||||
err = new DocumentNotFoundError(query.getQuery());
|
||||
err = new DocumentNotFoundError(query.getQuery(), query.model.modelName);
|
||||
}
|
||||
|
||||
return err;
|
||||
@@ -4316,7 +4358,20 @@ Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
|
||||
useNestedStrict = this.options.useNestedStrict;
|
||||
}
|
||||
|
||||
return castUpdate(this.schema, obj, {
|
||||
let schema = this.schema;
|
||||
const filter = this._conditions;
|
||||
if (schema != null &&
|
||||
utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) &&
|
||||
typeof filter[schema.options.discriminatorKey] !== 'object' &&
|
||||
schema.discriminators != null) {
|
||||
const discriminatorValue = filter[schema.options.discriminatorKey];
|
||||
const byValue = helpers.getDiscriminatorByValue(this.model, discriminatorValue);
|
||||
schema = schema.discriminators[discriminatorValue] ||
|
||||
(byValue && byValue.schema) ||
|
||||
schema;
|
||||
}
|
||||
|
||||
return castUpdate(schema, obj, {
|
||||
overwrite: overwrite,
|
||||
strict: strict,
|
||||
omitUndefined,
|
||||
@@ -4396,7 +4451,8 @@ function castDoc(query, overwrite) {
|
||||
*/
|
||||
|
||||
Query.prototype.populate = function() {
|
||||
if (arguments.length === 0) {
|
||||
// Bail when given no truthy arguments
|
||||
if (!Array.from(arguments).some(Boolean)) {
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -245,7 +245,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
|
||||
}
|
||||
// Any leftover plus paths must in the schema, so delete them (gh-7017)
|
||||
for (const key of Object.keys(fields || {})) {
|
||||
if (key.charAt(0) === '+') {
|
||||
if (key.startsWith('+')) {
|
||||
delete fields[key];
|
||||
}
|
||||
}
|
||||
|
||||
+33
-23
@@ -52,11 +52,12 @@ let id = 0;
|
||||
* - [collection](/docs/guide.html#collection): string - no default
|
||||
* - [id](/docs/guide.html#id): bool - defaults to true
|
||||
* - [_id](/docs/guide.html#_id): bool - defaults to true
|
||||
* - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
|
||||
* - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
|
||||
* - [read](/docs/guide.html#read): string
|
||||
* - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/)
|
||||
* - [shardKey](/docs/guide.html#shardKey): object - defaults to `null`
|
||||
* - [strict](/docs/guide.html#strict): bool - defaults to true
|
||||
* - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false
|
||||
* - [toJSON](/docs/guide.html#toJSON) - object - no default
|
||||
* - [toObject](/docs/guide.html#toObject) - object - no default
|
||||
* - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
|
||||
@@ -65,6 +66,9 @@ let id = 0;
|
||||
* - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v"
|
||||
* - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
|
||||
* - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
|
||||
* - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
|
||||
* - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
|
||||
* - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
@@ -312,7 +316,7 @@ Schema.prototype.clone = function() {
|
||||
if (this.discriminatorMapping != null) {
|
||||
s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
|
||||
}
|
||||
if (s.discriminators != null) {
|
||||
if (this.discriminators != null) {
|
||||
s.discriminators = Object.assign({}, this.discriminators);
|
||||
}
|
||||
|
||||
@@ -393,7 +397,7 @@ Schema.prototype.defaultOptions = function(options) {
|
||||
Schema.prototype.add = function add(obj, prefix) {
|
||||
if (obj instanceof Schema) {
|
||||
merge(this, obj);
|
||||
return;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Special case: setting top-level `_id` to false should convert to disabling
|
||||
@@ -567,7 +571,7 @@ Schema.prototype.path = function(path, obj) {
|
||||
console.log('WARN: ' + warnings[path]);
|
||||
}
|
||||
|
||||
if (typeof obj === 'object' && 'ref' in obj) {
|
||||
if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) {
|
||||
validateRef(obj.ref, path);
|
||||
}
|
||||
|
||||
@@ -601,9 +605,16 @@ Schema.prototype.path = function(path, obj) {
|
||||
// The '$' is to imply this path should never be stored in MongoDB so we
|
||||
// can easily build a regexp out of this path, and '*' to imply "any key."
|
||||
const mapPath = path + '.$*';
|
||||
this.paths[path + '.$*'] = this.interpretAsType(mapPath,
|
||||
obj.of || { type: {} }, this.options);
|
||||
schemaType.$__schemaType = this.paths[path + '.$*'];
|
||||
let _mapType = { type: {} };
|
||||
if (utils.hasUserDefinedProperty(obj, 'of')) {
|
||||
const isInlineSchema = utils.isPOJO(obj.of) &&
|
||||
Object.keys(obj.of).length > 0 &&
|
||||
!utils.hasUserDefinedProperty(obj.of, this.options.typeKey);
|
||||
_mapType = isInlineSchema ? new Schema(obj.of) : obj.of;
|
||||
}
|
||||
this.paths[mapPath] = this.interpretAsType(mapPath,
|
||||
_mapType, this.options);
|
||||
schemaType.$__schemaType = this.paths[mapPath];
|
||||
}
|
||||
|
||||
if (schemaType.$isSingleNested) {
|
||||
@@ -1026,7 +1037,7 @@ Schema.prototype.setupTimestamp = function(timestamps) {
|
||||
let ts = defaultTimestamp;
|
||||
if (this.isNew) {
|
||||
if (createdAt != null) {
|
||||
ts = this.getValue(createdAt);
|
||||
ts = this.$__getValue(createdAt);
|
||||
} else if (auto_id) {
|
||||
ts = this._id.getTimestamp();
|
||||
}
|
||||
@@ -1183,10 +1194,10 @@ Schema.prototype.queue = function(name, args) {
|
||||
*
|
||||
* // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
|
||||
* toySchema.pre(/^find/, function(next) {
|
||||
* console.log(this.getQuery());
|
||||
* console.log(this.getFilter());
|
||||
* });
|
||||
*
|
||||
* @param {String|RegExp} method or regular expression to match method name
|
||||
* @param {String|RegExp} The method name or regular expression to match method name
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
|
||||
* @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
|
||||
@@ -1236,7 +1247,7 @@ Schema.prototype.pre = function(name) {
|
||||
* console.log('this fires after the post find hook');
|
||||
* });
|
||||
*
|
||||
* @param {String|RegExp} method or regular expression to match method name
|
||||
* @param {String|RegExp} The method name or regular expression to match method name
|
||||
* @param {Object} [options]
|
||||
* @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
|
||||
* @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
|
||||
@@ -1347,21 +1358,21 @@ Schema.prototype.method = function(name, fn, options) {
|
||||
*
|
||||
* ####Example
|
||||
*
|
||||
* var schema = new Schema(..);
|
||||
* schema.static('findByName', function (name, callback) {
|
||||
* return this.find({ name: name }, callback);
|
||||
* const schema = new Schema(..);
|
||||
* // Equivalent to `schema.statics.findByName = function(name) {}`;
|
||||
* schema.static('findByName', function(name) {
|
||||
* return this.find({ name: name });
|
||||
* });
|
||||
*
|
||||
* var Drink = mongoose.model('Drink', schema);
|
||||
* Drink.findByName('sanpellegrino', function (err, drinks) {
|
||||
* //
|
||||
* });
|
||||
* const Drink = mongoose.model('Drink', schema);
|
||||
* await Drink.findByName('LaCroix');
|
||||
*
|
||||
* If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
|
||||
*
|
||||
* @param {String|Object} name
|
||||
* @param {Function} [fn]
|
||||
* @api public
|
||||
* @see Statics /docs/guide.html#statics
|
||||
*/
|
||||
|
||||
Schema.prototype.static = function(name, fn) {
|
||||
@@ -1531,7 +1542,7 @@ Schema.prototype.indexes = function() {
|
||||
*/
|
||||
|
||||
Schema.prototype.virtual = function(name, options) {
|
||||
if (options && options.ref) {
|
||||
if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
|
||||
if (!options.localField) {
|
||||
throw new Error('Reference virtuals require `localField` option');
|
||||
}
|
||||
@@ -1568,10 +1579,10 @@ Schema.prototype.virtual = function(name, options) {
|
||||
if (!this.$$populatedVirtuals) {
|
||||
this.$$populatedVirtuals = {};
|
||||
}
|
||||
if (name in this.$$populatedVirtuals) {
|
||||
if (this.$$populatedVirtuals.hasOwnProperty(name)) {
|
||||
return this.$$populatedVirtuals[name];
|
||||
}
|
||||
return null;
|
||||
return void 0;
|
||||
}).
|
||||
set(function(_v) {
|
||||
if (!this.$$populatedVirtuals) {
|
||||
@@ -1916,8 +1927,7 @@ Schema.prototype._getPathType = function(path) {
|
||||
*/
|
||||
|
||||
function isArrayFilter(piece) {
|
||||
return piece.indexOf('$[') === 0 &&
|
||||
piece.lastIndexOf(']') === piece.length - 1;
|
||||
return piece.startsWith('$[') && piece.endsWith(']');
|
||||
}
|
||||
|
||||
/*!
|
||||
|
||||
+17
-3
@@ -250,12 +250,26 @@ SchemaArray.prototype.cast = function(value, doc, init) {
|
||||
if (!value.length && doc) {
|
||||
const indexes = doc.schema.indexedPaths();
|
||||
|
||||
const arrayPath = this.path;
|
||||
for (i = 0, l = indexes.length; i < l; ++i) {
|
||||
const pathIndex = indexes[i][0][this.path];
|
||||
const pathIndex = indexes[i][0][arrayPath];
|
||||
if (pathIndex === '2dsphere' || pathIndex === '2d') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Special case: if this index is on the parent of what looks like
|
||||
// GeoJSON, skip setting the default to empty array re: #1668, #3233
|
||||
const arrayGeojsonPath = this.path.endsWith('.coordinates') ?
|
||||
this.path.substr(0, this.path.lastIndexOf('.')) : null;
|
||||
if (arrayGeojsonPath != null) {
|
||||
for (i = 0, l = indexes.length; i < l; ++i) {
|
||||
const pathIndex = indexes[i][0][arrayGeojsonPath];
|
||||
if (pathIndex === '2dsphere') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!(value && value.isMongooseArray)) {
|
||||
@@ -417,7 +431,7 @@ function cast$elemMatch(val) {
|
||||
for (let i = 0; i < numKeys; ++i) {
|
||||
const key = keys[i];
|
||||
const value = val[key];
|
||||
if (key.indexOf('$') === 0 && value) {
|
||||
if (key.startsWith('$') && value) {
|
||||
val[key] = this.castForQuery(key, value);
|
||||
}
|
||||
}
|
||||
@@ -474,11 +488,11 @@ handle.$gte =
|
||||
handle.$lt =
|
||||
handle.$lte =
|
||||
handle.$ne =
|
||||
handle.$nin =
|
||||
handle.$regex = SchemaArray.prototype.castForQuery;
|
||||
|
||||
// `$in` is special because you can also include an empty array in the query
|
||||
// like `$in: [1, []]`, see gh-5913
|
||||
handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin;
|
||||
handle.$in = SchemaType.prototype.$conditionalHandlers.$in;
|
||||
|
||||
/*!
|
||||
|
||||
+3
-1
@@ -7,6 +7,8 @@
|
||||
const handleBitwiseOperator = require('./operators/bitwise');
|
||||
const utils = require('../utils');
|
||||
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
const MongooseBuffer = require('../types/buffer');
|
||||
const SchemaType = require('../schematype');
|
||||
|
||||
@@ -125,7 +127,7 @@ SchemaBuffer.prototype.cast = function(value, doc, init) {
|
||||
const path = doc.$__fullPath(this.path);
|
||||
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
const pop = owner.populated(path, true);
|
||||
ret = new pop.options.model(value);
|
||||
ret = new pop.options[populateModelSymbol](value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
+3
-1
@@ -10,6 +10,8 @@ const Decimal128Type = require('../types/decimal128');
|
||||
const castDecimal128 = require('../cast/decimal128');
|
||||
const utils = require('../utils');
|
||||
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
let Document;
|
||||
|
||||
/**
|
||||
@@ -170,7 +172,7 @@ Decimal128.prototype.cast = function(value, doc, init) {
|
||||
!doc.$__.populated[path].options ||
|
||||
!doc.$__.populated[path].options.options ||
|
||||
!doc.$__.populated[path].options.options.lean) {
|
||||
ret = new pop.options.model(value);
|
||||
ret = new pop.options[populateModelSymbol](value);
|
||||
ret.$__.wasPopulated = true;
|
||||
}
|
||||
|
||||
|
||||
+14
-33
@@ -11,7 +11,7 @@ const SchemaType = require('../schematype');
|
||||
const discriminator = require('../helpers/model/discriminator');
|
||||
const util = require('util');
|
||||
const utils = require('../utils');
|
||||
const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;
|
||||
const getConstructor = require('../helpers/discriminator/getConstructor');
|
||||
|
||||
const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
|
||||
const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
|
||||
@@ -210,7 +210,7 @@ DocumentArray.prototype.doValidate = function(array, fn, scope, options) {
|
||||
// If you set the array index directly, the doc might not yet be
|
||||
// a full fledged mongoose subdoc, so make it into one.
|
||||
if (!(doc instanceof Subdocument)) {
|
||||
const Constructor = getConstructor(_this, array[i]);
|
||||
const Constructor = getConstructor(_this.casterConstructor, array[i]);
|
||||
doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
|
||||
}
|
||||
|
||||
@@ -258,7 +258,7 @@ DocumentArray.prototype.doValidateSync = function(array, scope) {
|
||||
// If you set the array index directly, the doc might not yet be
|
||||
// a full fledged mongoose subdoc, so make it into one.
|
||||
if (!(doc instanceof Subdocument)) {
|
||||
const Constructor = getConstructor(this, array[i]);
|
||||
const Constructor = getConstructor(this.casterConstructor, array[i]);
|
||||
doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
|
||||
}
|
||||
|
||||
@@ -297,7 +297,7 @@ DocumentArray.prototype.getDefault = function(scope) {
|
||||
ret[arrayParentSymbol] = null;
|
||||
|
||||
for (let i = 0; i < ret.length; ++i) {
|
||||
const Constructor = getConstructor(this, ret[i]);
|
||||
const Constructor = getConstructor(this.casterConstructor, ret[i]);
|
||||
ret[i] = new Constructor(ret[i], ret, undefined,
|
||||
undefined, i);
|
||||
}
|
||||
@@ -353,12 +353,17 @@ DocumentArray.prototype.cast = function(value, doc, init, prev, options) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const Constructor = getConstructor(this, value[i]);
|
||||
const Constructor = getConstructor(this.casterConstructor, value[i]);
|
||||
|
||||
// Check if the document has a different schema (re gh-3701)
|
||||
if ((value[i].$__) &&
|
||||
!(value[i] instanceof Constructor)) {
|
||||
value[i] = value[i].toObject({ transform: false, virtuals: false });
|
||||
value[i] = value[i].toObject({
|
||||
transform: false,
|
||||
// Special case: if different model, but same schema, apply virtuals
|
||||
// re: gh-7898
|
||||
virtuals: value[i].schema === Constructor.schema
|
||||
});
|
||||
}
|
||||
|
||||
if (value[i] instanceof Subdocument) {
|
||||
@@ -377,7 +382,7 @@ DocumentArray.prototype.cast = function(value, doc, init, prev, options) {
|
||||
subdoc = new Constructor(null, value, true, selected, i);
|
||||
value[i] = subdoc.init(value[i]);
|
||||
} else {
|
||||
if (prev && (subdoc = prev.id(value[i]._id))) {
|
||||
if (prev && typeof prev.id === 'function') {
|
||||
subdoc = prev.id(value[i]._id);
|
||||
}
|
||||
|
||||
@@ -410,30 +415,6 @@ DocumentArray.prototype.cast = function(value, doc, init, prev, options) {
|
||||
return value;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Find the correct subdoc constructor, taking into account discriminators
|
||||
*/
|
||||
|
||||
function getConstructor(docArray, subdoc) {
|
||||
let Constructor = docArray.casterConstructor;
|
||||
const schema = Constructor.schema;
|
||||
const discriminatorKey = schema.options.discriminatorKey;
|
||||
const discriminatorValue = subdoc[discriminatorKey];
|
||||
if (Constructor.discriminators && typeof discriminatorValue === 'string') {
|
||||
if (Constructor.discriminators[discriminatorValue]) {
|
||||
Constructor = Constructor.discriminators[discriminatorValue];
|
||||
} else {
|
||||
const constructorByValue = getDiscriminatorByValue(Constructor,
|
||||
discriminatorValue);
|
||||
if (constructorByValue) {
|
||||
Constructor = constructorByValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Constructor;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
@@ -483,12 +464,12 @@ function scopePaths(array, fields, init) {
|
||||
|
||||
while (i--) {
|
||||
key = keys[i];
|
||||
if (key.indexOf(path) === 0) {
|
||||
if (key.startsWith(path)) {
|
||||
sub = key.substring(path.length);
|
||||
if (sub === '$') {
|
||||
continue;
|
||||
}
|
||||
if (sub.indexOf('$.') === 0) {
|
||||
if (sub.startsWith('$.')) {
|
||||
sub = sub.substr(2);
|
||||
}
|
||||
hasKeys || (hasKeys = true);
|
||||
|
||||
+5
-43
@@ -13,7 +13,7 @@ const castToNumber = require('./operators/helpers').castToNumber;
|
||||
const discriminator = require('../helpers/model/discriminator');
|
||||
const geospatial = require('./operators/geospatial');
|
||||
const get = require('../helpers/get');
|
||||
const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;
|
||||
const getConstructor = require('../helpers/discriminator/getConstructor');
|
||||
const internalToObjectOptions = require('../options').internalToObjectOptions;
|
||||
|
||||
let Subdocument;
|
||||
@@ -149,20 +149,7 @@ Embedded.prototype.cast = function(val, doc, init, priorVal) {
|
||||
throw new ObjectExpectedError(this.path, val);
|
||||
}
|
||||
|
||||
let Constructor = this.caster;
|
||||
const discriminatorKey = Constructor.schema.options.discriminatorKey;
|
||||
if (val != null &&
|
||||
Constructor.discriminators &&
|
||||
typeof val[discriminatorKey] === 'string') {
|
||||
if (Constructor.discriminators[val[discriminatorKey]]) {
|
||||
Constructor = Constructor.discriminators[val[discriminatorKey]];
|
||||
} else {
|
||||
const constructorByValue = getDiscriminatorByValue(Constructor, val[discriminatorKey]);
|
||||
if (constructorByValue) {
|
||||
Constructor = constructorByValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
const Constructor = getConstructor(this.caster, val);
|
||||
|
||||
let subdoc;
|
||||
|
||||
@@ -216,20 +203,7 @@ Embedded.prototype.castForQuery = function($conditional, val) {
|
||||
val = this._applySetters(val);
|
||||
}
|
||||
|
||||
let Constructor = this.caster;
|
||||
const discriminatorKey = Constructor.schema.options.discriminatorKey;
|
||||
if (val != null &&
|
||||
Constructor.discriminators &&
|
||||
typeof val[discriminatorKey] === 'string') {
|
||||
if (Constructor.discriminators[val[discriminatorKey]]) {
|
||||
Constructor = Constructor.discriminators[val[discriminatorKey]];
|
||||
} else {
|
||||
const constructorByValue = getDiscriminatorByValue(Constructor, val[discriminatorKey]);
|
||||
if (constructorByValue) {
|
||||
Constructor = constructorByValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
const Constructor = getConstructor(this.caster, val);
|
||||
|
||||
try {
|
||||
val = new Constructor(val);
|
||||
@@ -250,20 +224,7 @@ Embedded.prototype.castForQuery = function($conditional, val) {
|
||||
*/
|
||||
|
||||
Embedded.prototype.doValidate = function(value, fn, scope, options) {
|
||||
let Constructor = this.caster;
|
||||
const discriminatorKey = Constructor.schema.options.discriminatorKey;
|
||||
if (value != null &&
|
||||
Constructor.discriminators &&
|
||||
typeof value[discriminatorKey] === 'string') {
|
||||
if (Constructor.discriminators[value[discriminatorKey]]) {
|
||||
Constructor = Constructor.discriminators[value[discriminatorKey]];
|
||||
} else {
|
||||
const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]);
|
||||
if (constructorByValue) {
|
||||
Constructor = constructorByValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
const Constructor = getConstructor(this.caster, value);
|
||||
|
||||
if (options && options.skipSchemaValidators) {
|
||||
if (!(value instanceof Constructor)) {
|
||||
@@ -328,5 +289,6 @@ Embedded.prototype.clone = function() {
|
||||
const options = Object.assign({}, this.options);
|
||||
const schematype = new this.constructor(this.schema, this.path, options);
|
||||
schematype.validators = this.validators.slice();
|
||||
schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
|
||||
return schematype;
|
||||
};
|
||||
|
||||
+3
-1
@@ -10,6 +10,8 @@ const castNumber = require('../cast/number');
|
||||
const handleBitwiseOperator = require('./operators/bitwise');
|
||||
const utils = require('../utils');
|
||||
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
const CastError = SchemaType.CastError;
|
||||
let Document;
|
||||
|
||||
@@ -293,7 +295,7 @@ SchemaNumber.prototype.cast = function(value, doc, init) {
|
||||
const path = doc.$__fullPath(this.path);
|
||||
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
const pop = owner.populated(path, true);
|
||||
const ret = new pop.options.model(value);
|
||||
const ret = new pop.options[populateModelSymbol](value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
|
||||
+3
-1
@@ -9,6 +9,8 @@ const SchemaType = require('../schematype');
|
||||
const oid = require('../types/objectid');
|
||||
const utils = require('../utils');
|
||||
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
const CastError = SchemaType.CastError;
|
||||
let Document;
|
||||
|
||||
@@ -226,7 +228,7 @@ ObjectId.prototype.cast = function(value, doc, init) {
|
||||
!doc.$__.populated[path].options ||
|
||||
!doc.$__.populated[path].options.options ||
|
||||
!doc.$__.populated[path].options.options.lean) {
|
||||
ret = new pop.options.model(value);
|
||||
ret = new pop.options[populateModelSymbol](value);
|
||||
ret.$__.wasPopulated = true;
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -10,6 +10,8 @@ const MongooseError = require('../error');
|
||||
const castString = require('../cast/string');
|
||||
const utils = require('../utils');
|
||||
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
let Document;
|
||||
|
||||
/**
|
||||
@@ -537,7 +539,7 @@ SchemaString.prototype.cast = function(value, doc, init) {
|
||||
const path = doc.$__fullPath(this.path);
|
||||
const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
|
||||
const pop = owner.populated(path, true);
|
||||
const ret = new pop.options.model(value);
|
||||
const ret = new pop.options[populateModelSymbol](value);
|
||||
ret.$__.wasPopulated = true;
|
||||
return ret;
|
||||
}
|
||||
@@ -577,7 +579,7 @@ SchemaString.prototype.$conditionalHandlers =
|
||||
$gte: handleSingle,
|
||||
$lt: handleSingle,
|
||||
$lte: handleSingle,
|
||||
$options: handleSingle,
|
||||
$options: String,
|
||||
$regex: handleSingle,
|
||||
$not: handleSingle
|
||||
});
|
||||
|
||||
+60
-2
@@ -8,6 +8,7 @@ const MongooseError = require('./error');
|
||||
const $exists = require('./schema/operators/exists');
|
||||
const $type = require('./schema/operators/type');
|
||||
const get = require('./helpers/get');
|
||||
const handleImmutable = require('./helpers/schematype/handleImmutable');
|
||||
const immediate = require('./helpers/immediate');
|
||||
const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
|
||||
const util = require('util');
|
||||
@@ -44,6 +45,11 @@ function SchemaType(path, options, instance) {
|
||||
this.options = options;
|
||||
this._index = null;
|
||||
this.selected;
|
||||
if (utils.hasUserDefinedProperty(options, 'immutable')) {
|
||||
this.$immutable = options.immutable;
|
||||
|
||||
handleImmutable(this);
|
||||
}
|
||||
|
||||
for (const prop in options) {
|
||||
if (this[prop] && typeof this[prop] === 'function') {
|
||||
@@ -300,7 +306,7 @@ SchemaType.prototype.text = function(bool) {
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var s = new Schema({ name: { type: String, sparse: true })
|
||||
* var s = new Schema({ name: { type: String, sparse: true } });
|
||||
* Schema.path('name').index({ sparse: true });
|
||||
*
|
||||
* @param {Boolean} bool
|
||||
@@ -327,6 +333,56 @@ SchemaType.prototype.sparse = function(bool) {
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines this path as immutable. Mongoose prevents you from changing
|
||||
* immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew).
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* const schema = new Schema({
|
||||
* name: { type: String, immutable: true },
|
||||
* age: Number
|
||||
* });
|
||||
* const Model = mongoose.model('Test', schema);
|
||||
*
|
||||
* await Model.create({ name: 'test' });
|
||||
* const doc = await Model.findOne();
|
||||
*
|
||||
* doc.isNew; // false
|
||||
* doc.name = 'new name';
|
||||
* doc.name; // 'test', because `name` is immutable
|
||||
*
|
||||
* Mongoose also prevents changing immutable properties using `updateOne()`
|
||||
* and `updateMany()` based on [strict mode](/docs/guide.html#strict).
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* // Mongoose will strip out the `name` update, because `name` is immutable
|
||||
* Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
|
||||
*
|
||||
* // If `strict` is set to 'throw', Mongoose will throw an error if you
|
||||
* // update `name`
|
||||
* const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
|
||||
* then(() => null, err => err);
|
||||
* err.name; // StrictModeError
|
||||
*
|
||||
* // If `strict` is `false`, Mongoose allows updating `name` even though
|
||||
* // the property is immutable.
|
||||
* Model.updateOne({}, { name: 'test2' }, { strict: false });
|
||||
*
|
||||
* @param {Boolean} bool
|
||||
* @return {SchemaType} this
|
||||
* @see isNew /docs/api.html#document_Document-isNew
|
||||
* @api public
|
||||
*/
|
||||
|
||||
SchemaType.prototype.immutable = function(bool) {
|
||||
this.$immutable = bool;
|
||||
handleImmutable(this);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a setter to this schematype.
|
||||
*
|
||||
@@ -1024,6 +1080,7 @@ SchemaType.prototype.doValidate = function(value, fn, scope, options) {
|
||||
function(ok) { validate(ok, validatorProperties); },
|
||||
function(error) {
|
||||
validatorProperties.reason = error;
|
||||
validatorProperties.message = error.message;
|
||||
ok = false;
|
||||
validate(ok, validatorProperties);
|
||||
});
|
||||
@@ -1071,6 +1128,7 @@ function asyncValidate(validator, scope, value, props, cb) {
|
||||
called = true;
|
||||
|
||||
props.reason = error;
|
||||
props.message = error.message;
|
||||
cb(false, props);
|
||||
});
|
||||
}
|
||||
@@ -1253,7 +1311,7 @@ SchemaType.prototype.$conditionalHandlers = {
|
||||
$eq: handleSingle,
|
||||
$in: handle$in,
|
||||
$ne: handleSingle,
|
||||
$nin: handleArray,
|
||||
$nin: handle$in,
|
||||
$exists: $exists,
|
||||
$type: $type
|
||||
};
|
||||
|
||||
+8
-827
@@ -5,20 +5,14 @@
|
||||
'use strict';
|
||||
|
||||
const CoreMongooseArray = require('./core_array');
|
||||
const EmbeddedDocument = require('./embedded');
|
||||
const Document = require('../document');
|
||||
const ObjectId = require('./objectid');
|
||||
const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths');
|
||||
const get = require('../helpers/get');
|
||||
const internalToObjectOptions = require('../options').internalToObjectOptions;
|
||||
const utils = require('../utils');
|
||||
const util = require('util');
|
||||
|
||||
const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
|
||||
const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
|
||||
const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
|
||||
const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol;
|
||||
const isMongooseObject = utils.isMongooseObject;
|
||||
|
||||
const _basePush = Array.prototype.push;
|
||||
|
||||
/**
|
||||
* Mongoose Array constructor.
|
||||
@@ -39,24 +33,20 @@ function MongooseArray(values, path, doc) {
|
||||
// TODO: replace this with `new CoreMongooseArray().concat()` when we remove
|
||||
// support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png
|
||||
const arr = new CoreMongooseArray();
|
||||
arr[arrayAtomicsSymbol] = {};
|
||||
|
||||
if (Array.isArray(values)) {
|
||||
values.forEach(v => { arr.push(v); });
|
||||
}
|
||||
const len = values.length;
|
||||
for (let i = 0; i < len; ++i) {
|
||||
_basePush.call(arr, values[i]);
|
||||
}
|
||||
|
||||
const keysMA = Object.keys(MongooseArray.mixin);
|
||||
const numKeys = keysMA.length;
|
||||
for (let i = 0; i < numKeys; ++i) {
|
||||
arr[keysMA[i]] = MongooseArray.mixin[keysMA[i]];
|
||||
arr[arrayAtomicsSymbol] = values[arrayAtomicsSymbol] || {};
|
||||
}
|
||||
|
||||
arr[arrayPathSymbol] = path;
|
||||
arr.validators = [];
|
||||
arr[arrayAtomicsSymbol] = {};
|
||||
arr[arraySchemaSymbol] = void 0;
|
||||
if (util.inspect.custom) {
|
||||
arr[util.inspect.custom] = arr.inspect;
|
||||
}
|
||||
|
||||
// Because doc comes from the context of another function, doc === global
|
||||
// can happen if there was a null somewhere up the chain (see #3020)
|
||||
@@ -70,815 +60,6 @@ function MongooseArray(values, path, doc) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
MongooseArray.mixin = {
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
toBSON: function() {
|
||||
return this.toObject(internalToObjectOptions);
|
||||
},
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$parent: function() {
|
||||
return this[arrayParentSymbol];
|
||||
},
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$schema: function() {
|
||||
return this[arraySchemaSymbol];
|
||||
},
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$path: function() {
|
||||
return this[arrayPathSymbol];
|
||||
},
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$atomics: function() {
|
||||
return this[arrayAtomicsSymbol];
|
||||
},
|
||||
|
||||
/**
|
||||
* Casts a member based on this arrays schema.
|
||||
*
|
||||
* @param {any} value
|
||||
* @return value the casted value
|
||||
* @method _cast
|
||||
* @api private
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_cast: function(value) {
|
||||
let populated = false;
|
||||
let Model;
|
||||
|
||||
if (this[arrayParentSymbol]) {
|
||||
populated = this[arrayParentSymbol].populated(this[arrayPathSymbol], true);
|
||||
}
|
||||
|
||||
if (populated && value !== null && value !== undefined) {
|
||||
// cast to the populated Models schema
|
||||
Model = populated.options.model || populated.options.Model;
|
||||
|
||||
// only objects are permitted so we can safely assume that
|
||||
// non-objects are to be interpreted as _id
|
||||
if (Buffer.isBuffer(value) ||
|
||||
value instanceof ObjectId || !utils.isObject(value)) {
|
||||
value = {_id: value};
|
||||
}
|
||||
|
||||
// gh-2399
|
||||
// we should cast model only when it's not a discriminator
|
||||
const isDisc = value.schema && value.schema.discriminatorMapping &&
|
||||
value.schema.discriminatorMapping.key !== undefined;
|
||||
if (!isDisc) {
|
||||
value = new Model(value);
|
||||
}
|
||||
return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], true);
|
||||
}
|
||||
|
||||
return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], false);
|
||||
},
|
||||
|
||||
/**
|
||||
* Marks this array as modified.
|
||||
*
|
||||
* If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
|
||||
*
|
||||
* @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array
|
||||
* @param {String} embeddedPath the path which changed in the embeddedDoc
|
||||
* @method _markModified
|
||||
* @api private
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_markModified: function(elem, embeddedPath) {
|
||||
const parent = this[arrayParentSymbol];
|
||||
let dirtyPath;
|
||||
|
||||
if (parent) {
|
||||
dirtyPath = this[arrayPathSymbol];
|
||||
|
||||
if (arguments.length) {
|
||||
if (embeddedPath != null) {
|
||||
// an embedded doc bubbled up the change
|
||||
dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath;
|
||||
} else {
|
||||
// directly set an index
|
||||
dirtyPath = dirtyPath + '.' + elem;
|
||||
}
|
||||
}
|
||||
|
||||
parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent);
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Register an atomic operation with the parent.
|
||||
*
|
||||
* @param {Array} op operation
|
||||
* @param {any} val
|
||||
* @method _registerAtomic
|
||||
* @api private
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_registerAtomic: function(op, val) {
|
||||
if (op === '$set') {
|
||||
// $set takes precedence over all other ops.
|
||||
// mark entire array modified.
|
||||
this[arrayAtomicsSymbol] = {$set: val};
|
||||
cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]);
|
||||
this._markModified();
|
||||
return this;
|
||||
}
|
||||
|
||||
const atomics = this[arrayAtomicsSymbol];
|
||||
|
||||
// reset pop/shift after save
|
||||
if (op === '$pop' && !('$pop' in atomics)) {
|
||||
const _this = this;
|
||||
this[arrayParentSymbol].once('save', function() {
|
||||
_this._popped = _this._shifted = null;
|
||||
});
|
||||
}
|
||||
|
||||
// check for impossible $atomic combos (Mongo denies more than one
|
||||
// $atomic op on a single path
|
||||
if (this[arrayAtomicsSymbol].$set ||
|
||||
Object.keys(atomics).length && !(op in atomics)) {
|
||||
// a different op was previously registered.
|
||||
// save the entire thing.
|
||||
this[arrayAtomicsSymbol] = {$set: this};
|
||||
return this;
|
||||
}
|
||||
|
||||
let selector;
|
||||
|
||||
if (op === '$pullAll' || op === '$addToSet') {
|
||||
atomics[op] || (atomics[op] = []);
|
||||
atomics[op] = atomics[op].concat(val);
|
||||
} else if (op === '$pullDocs') {
|
||||
const pullOp = atomics['$pull'] || (atomics['$pull'] = {});
|
||||
if (val[0] instanceof EmbeddedDocument) {
|
||||
selector = pullOp['$or'] || (pullOp['$or'] = []);
|
||||
Array.prototype.push.apply(selector, val.map(function(v) {
|
||||
return v.toObject({transform: false, virtuals: false});
|
||||
}));
|
||||
} else {
|
||||
selector = pullOp['_id'] || (pullOp['_id'] = {$in: []});
|
||||
selector['$in'] = selector['$in'].concat(val);
|
||||
}
|
||||
} else if (op === '$push') {
|
||||
atomics.$push = atomics.$push || { $each: [] };
|
||||
atomics.$push.$each = atomics.$push.$each.concat(val);
|
||||
} else {
|
||||
atomics[op] = val;
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.
|
||||
*
|
||||
* If no atomics exist, we return all array values after conversion.
|
||||
*
|
||||
* @return {Array}
|
||||
* @method $__getAtomics
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @api private
|
||||
*/
|
||||
|
||||
$__getAtomics: function() {
|
||||
const ret = [];
|
||||
const keys = Object.keys(this[arrayAtomicsSymbol]);
|
||||
let i = keys.length;
|
||||
|
||||
const opts = Object.assign({}, internalToObjectOptions, { _isNested: true });
|
||||
|
||||
if (i === 0) {
|
||||
ret[0] = ['$set', this.toObject(opts)];
|
||||
return ret;
|
||||
}
|
||||
|
||||
while (i--) {
|
||||
const op = keys[i];
|
||||
let val = this[arrayAtomicsSymbol][op];
|
||||
|
||||
// the atomic values which are arrays are not MongooseArrays. we
|
||||
// need to convert their elements as if they were MongooseArrays
|
||||
// to handle populated arrays versus DocumentArrays properly.
|
||||
if (isMongooseObject(val)) {
|
||||
val = val.toObject(opts);
|
||||
} else if (Array.isArray(val)) {
|
||||
val = this.toObject.call(val, opts);
|
||||
} else if (val != null && Array.isArray(val.$each)) {
|
||||
val.$each = this.toObject.call(val.$each, opts);
|
||||
} else if (val != null && typeof val.valueOf === 'function') {
|
||||
val = val.valueOf();
|
||||
}
|
||||
|
||||
if (op === '$addToSet') {
|
||||
val = {$each: val};
|
||||
}
|
||||
|
||||
ret.push([op, val]);
|
||||
}
|
||||
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the number of pending atomic operations to send to the db for this array.
|
||||
*
|
||||
* @api private
|
||||
* @return {Number}
|
||||
* @method hasAtomics
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
hasAtomics: function hasAtomics() {
|
||||
if (!(this[arrayAtomicsSymbol] && this[arrayAtomicsSymbol].constructor.name === 'Object')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Object.keys(this[arrayAtomicsSymbol]).length;
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal helper for .map()
|
||||
*
|
||||
* @api private
|
||||
* @return {Number}
|
||||
* @method _mapCast
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
_mapCast: function(val, index) {
|
||||
return this._cast(val, this.length + index);
|
||||
},
|
||||
|
||||
/**
|
||||
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
|
||||
*
|
||||
* @param {Object} [args...]
|
||||
* @api public
|
||||
* @method push
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
push: function() {
|
||||
_checkManualPopulation(this, arguments);
|
||||
let values = [].map.call(arguments, this._mapCast, this);
|
||||
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol], undefined,
|
||||
undefined, { skipDocumentArrayCast: true });
|
||||
const ret = [].push.apply(this, values);
|
||||
|
||||
this._registerAtomic('$push', values);
|
||||
this._markModified();
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pushes items to the array non-atomically.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @param {any} [args...]
|
||||
* @api public
|
||||
* @method nonAtomicPush
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
nonAtomicPush: function() {
|
||||
const values = [].map.call(arguments, this._mapCast, this);
|
||||
const ret = [].push.apply(this, values);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pops the array atomically at most one time per document `save()`.
|
||||
*
|
||||
* #### NOTE:
|
||||
*
|
||||
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
|
||||
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
|
||||
*
|
||||
* doc.array = [1,2,3];
|
||||
*
|
||||
* var popped = doc.array.$pop();
|
||||
* console.log(popped); // 3
|
||||
* console.log(doc.array); // [1,2]
|
||||
*
|
||||
* // no affect
|
||||
* popped = doc.array.$pop();
|
||||
* console.log(doc.array); // [1,2]
|
||||
*
|
||||
* doc.save(function (err) {
|
||||
* if (err) return handleError(err);
|
||||
*
|
||||
* // we saved, now $pop works again
|
||||
* popped = doc.array.$pop();
|
||||
* console.log(popped); // 2
|
||||
* console.log(doc.array); // [1]
|
||||
* })
|
||||
*
|
||||
* @api public
|
||||
* @method $pop
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
|
||||
* @method $pop
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
$pop: function() {
|
||||
this._registerAtomic('$pop', 1);
|
||||
this._markModified();
|
||||
|
||||
// only allow popping once
|
||||
if (this._popped) {
|
||||
return;
|
||||
}
|
||||
this._popped = true;
|
||||
|
||||
return [].pop.call(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @see MongooseArray#$pop #types_array_MongooseArray-%24pop
|
||||
* @api public
|
||||
* @method pop
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
pop: function() {
|
||||
const ret = [].pop.call(this);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Atomically shifts the array at most one time per document `save()`.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
|
||||
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
|
||||
*
|
||||
* doc.array = [1,2,3];
|
||||
*
|
||||
* var shifted = doc.array.$shift();
|
||||
* console.log(shifted); // 1
|
||||
* console.log(doc.array); // [2,3]
|
||||
*
|
||||
* // no affect
|
||||
* shifted = doc.array.$shift();
|
||||
* console.log(doc.array); // [2,3]
|
||||
*
|
||||
* doc.save(function (err) {
|
||||
* if (err) return handleError(err);
|
||||
*
|
||||
* // we saved, now $shift works again
|
||||
* shifted = doc.array.$shift();
|
||||
* console.log(shifted ); // 2
|
||||
* console.log(doc.array); // [3]
|
||||
* })
|
||||
*
|
||||
* @api public
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @method $shift
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
|
||||
*/
|
||||
|
||||
$shift: function $shift() {
|
||||
this._registerAtomic('$pop', -1);
|
||||
this._markModified();
|
||||
|
||||
// only allow shifting once
|
||||
if (this._shifted) {
|
||||
return;
|
||||
}
|
||||
this._shifted = true;
|
||||
|
||||
return [].shift.call(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* doc.array = [2,3];
|
||||
* var res = doc.array.shift();
|
||||
* console.log(res) // 2
|
||||
* console.log(doc.array) // [3]
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method shift
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
shift: function() {
|
||||
const ret = [].shift.call(this);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pulls items from the array atomically. Equality is determined by casting
|
||||
* the provided value to an embedded document and comparing using
|
||||
* [the `Document.equals()` function.](./api.html#document_Document-equals)
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* doc.array.pull(ObjectId)
|
||||
* doc.array.pull({ _id: 'someId' })
|
||||
* doc.array.pull(36)
|
||||
* doc.array.pull('tag 1', 'tag 2')
|
||||
*
|
||||
* To remove a document from a subdocument array we may pass an object with a matching `_id`.
|
||||
*
|
||||
* doc.subdocs.push({ _id: 4815162342 })
|
||||
* doc.subdocs.pull({ _id: 4815162342 }) // removed
|
||||
*
|
||||
* Or we may passing the _id directly and let mongoose take care of it.
|
||||
*
|
||||
* doc.subdocs.push({ _id: 4815162342 })
|
||||
* doc.subdocs.pull(4815162342); // works
|
||||
*
|
||||
* The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.
|
||||
*
|
||||
* @param {any} [args...]
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
|
||||
* @api public
|
||||
* @method pull
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
pull: function() {
|
||||
const values = [].map.call(arguments, this._cast, this);
|
||||
const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]);
|
||||
let i = cur.length;
|
||||
let mem;
|
||||
|
||||
while (i--) {
|
||||
mem = cur[i];
|
||||
if (mem instanceof Document) {
|
||||
const some = values.some(function(v) {
|
||||
return mem.equals(v);
|
||||
});
|
||||
if (some) {
|
||||
[].splice.call(cur, i, 1);
|
||||
}
|
||||
} else if (~cur.indexOf.call(values, mem)) {
|
||||
[].splice.call(cur, i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (values[0] instanceof EmbeddedDocument) {
|
||||
this._registerAtomic('$pullDocs', values.map(function(v) {
|
||||
return v._id || v;
|
||||
}));
|
||||
} else {
|
||||
this._registerAtomic('$pullAll', values);
|
||||
}
|
||||
|
||||
this._markModified();
|
||||
|
||||
// Might have modified child paths and then pulled, like
|
||||
// `doc.children[1].name = 'test';` followed by
|
||||
// `doc.children.remove(doc.children[0]);`. In this case we fall back
|
||||
// to a `$set` on the whole array. See #3511
|
||||
if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) {
|
||||
this._registerAtomic('$set', this);
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method splice
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
splice: function splice() {
|
||||
let ret;
|
||||
|
||||
_checkManualPopulation(this, Array.prototype.slice.call(arguments, 2));
|
||||
|
||||
if (arguments.length) {
|
||||
const vals = [];
|
||||
for (let i = 0; i < arguments.length; ++i) {
|
||||
vals[i] = i < 2 ?
|
||||
arguments[i] :
|
||||
this._cast(arguments[i], arguments[0] + (i - 2));
|
||||
}
|
||||
ret = [].splice.apply(this, vals);
|
||||
this._registerAtomic('$set', this);
|
||||
}
|
||||
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method unshift
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
unshift: function() {
|
||||
_checkManualPopulation(this, arguments);
|
||||
|
||||
let values = [].map.call(arguments, this._cast, this);
|
||||
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
|
||||
[].unshift.apply(this, values);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return this.length;
|
||||
},
|
||||
|
||||
/**
|
||||
* Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method sort
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
sort: function() {
|
||||
const ret = [].sort.apply(this, arguments);
|
||||
this._registerAtomic('$set', this);
|
||||
return ret;
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds values to the array if not already present.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* console.log(doc.array) // [2,3,4]
|
||||
* var added = doc.array.addToSet(4,5);
|
||||
* console.log(doc.array) // [2,3,4,5]
|
||||
* console.log(added) // [5]
|
||||
*
|
||||
* @param {any} [args...]
|
||||
* @return {Array} the values that were added
|
||||
* @memberOf MongooseArray
|
||||
* @api public
|
||||
* @method addToSet
|
||||
*/
|
||||
|
||||
addToSet: function addToSet() {
|
||||
_checkManualPopulation(this, arguments);
|
||||
|
||||
let values = [].map.call(arguments, this._mapCast, this);
|
||||
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
|
||||
const added = [];
|
||||
let type = '';
|
||||
if (values[0] instanceof EmbeddedDocument) {
|
||||
type = 'doc';
|
||||
} else if (values[0] instanceof Date) {
|
||||
type = 'date';
|
||||
}
|
||||
|
||||
values.forEach(function(v) {
|
||||
let found;
|
||||
const val = +v;
|
||||
switch (type) {
|
||||
case 'doc':
|
||||
found = this.some(function(doc) {
|
||||
return doc.equals(v);
|
||||
});
|
||||
break;
|
||||
case 'date':
|
||||
found = this.some(function(d) {
|
||||
return +d === val;
|
||||
});
|
||||
break;
|
||||
default:
|
||||
found = ~this.indexOf(v);
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
[].push.call(this, v);
|
||||
this._registerAtomic('$addToSet', v);
|
||||
this._markModified();
|
||||
[].push.call(added, v);
|
||||
}
|
||||
}, this);
|
||||
|
||||
return added;
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the casted `val` at index `i` and marks the array modified.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* // given documents based on the following
|
||||
* var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
|
||||
*
|
||||
* var doc = new Doc({ array: [2,3,4] })
|
||||
*
|
||||
* console.log(doc.array) // [2,3,4]
|
||||
*
|
||||
* doc.array.set(1,"5");
|
||||
* console.log(doc.array); // [2,5,4] // properly cast to number
|
||||
* doc.save() // the change is saved
|
||||
*
|
||||
* // VS not using array#set
|
||||
* doc.array[1] = "5";
|
||||
* console.log(doc.array); // [2,"5",4] // no casting
|
||||
* doc.save() // change is not saved
|
||||
*
|
||||
* @return {Array} this
|
||||
* @api public
|
||||
* @method set
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
set: function set(i, val) {
|
||||
const value = this._cast(val, i);
|
||||
this[i] = value;
|
||||
this._markModified(i);
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a native js Array.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {Array}
|
||||
* @api public
|
||||
* @method toObject
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
toObject: function(options) {
|
||||
if (options && options.depopulate) {
|
||||
options = utils.clone(options);
|
||||
options._isNested = true;
|
||||
return this.map(function(doc) {
|
||||
return doc instanceof Document
|
||||
? doc.toObject(options)
|
||||
: doc;
|
||||
});
|
||||
}
|
||||
|
||||
return this.slice();
|
||||
},
|
||||
|
||||
/**
|
||||
* Helper for console.log
|
||||
*
|
||||
* @api public
|
||||
* @method inspect
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
inspect: function() {
|
||||
return JSON.stringify(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Return the index of `obj` or `-1` if not found.
|
||||
*
|
||||
* @param {Object} obj the item to look for
|
||||
* @return {Number}
|
||||
* @api public
|
||||
* @method indexOf
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
indexOf: function indexOf(obj) {
|
||||
if (obj instanceof ObjectId) {
|
||||
obj = obj.toString();
|
||||
}
|
||||
for (let i = 0, len = this.length; i < len; ++i) {
|
||||
if (obj == this[i]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Return whether or not the `obj` is included in the array.
|
||||
*
|
||||
* @param {Object} obj the item to check
|
||||
* @return {Boolean}
|
||||
* @api public
|
||||
* @method includes
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
includes: function includes(obj) {
|
||||
return this.indexOf(obj) !== -1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Alias of [pull](#types_array_MongooseArray-pull)
|
||||
*
|
||||
* @see MongooseArray#pull #types_array_MongooseArray-pull
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
|
||||
* @api public
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @method remove
|
||||
*/
|
||||
|
||||
MongooseArray.mixin.remove = MongooseArray.mixin.pull;
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function _isAllSubdocs(docs, ref) {
|
||||
if (!ref) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < docs.length; ++i) {
|
||||
const arg = docs[i];
|
||||
if (arg == null) {
|
||||
return false;
|
||||
}
|
||||
const model = arg.constructor;
|
||||
if (!(arg instanceof Document) ||
|
||||
(model.modelName !== ref && model.baseModelName !== ref)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function _checkManualPopulation(arr, docs) {
|
||||
const ref = arr == null ?
|
||||
null :
|
||||
get(arr[arraySchemaSymbol], 'caster.options.ref', null);
|
||||
if (arr.length === 0 &&
|
||||
docs.length > 0) {
|
||||
if (_isAllSubdocs(docs, ref)) {
|
||||
arr[arrayParentSymbol].populated(arr[arrayPathSymbol], [], { model: docs[0].constructor });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
+840
-2
@@ -1,5 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
const Document = require('../document');
|
||||
const EmbeddedDocument = require('./embedded');
|
||||
const ObjectId = require('./objectid');
|
||||
const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths');
|
||||
const get = require('../helpers/get');
|
||||
const internalToObjectOptions = require('../options').internalToObjectOptions;
|
||||
const utils = require('../utils');
|
||||
const util = require('util');
|
||||
|
||||
const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
|
||||
const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
|
||||
const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
|
||||
const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol;
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
const _basePush = Array.prototype.push;
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
@@ -9,7 +26,828 @@ class CoreMongooseArray extends Array {
|
||||
return true;
|
||||
}
|
||||
|
||||
remove() {}
|
||||
/**
|
||||
* Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.
|
||||
*
|
||||
* If no atomics exist, we return all array values after conversion.
|
||||
*
|
||||
* @return {Array}
|
||||
* @method $__getAtomics
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @api private
|
||||
*/
|
||||
|
||||
$__getAtomics() {
|
||||
const ret = [];
|
||||
const keys = Object.keys(this[arrayAtomicsSymbol]);
|
||||
let i = keys.length;
|
||||
|
||||
const opts = Object.assign({}, internalToObjectOptions, { _isNested: true });
|
||||
|
||||
if (i === 0) {
|
||||
ret[0] = ['$set', this.toObject(opts)];
|
||||
return ret;
|
||||
}
|
||||
|
||||
while (i--) {
|
||||
const op = keys[i];
|
||||
let val = this[arrayAtomicsSymbol][op];
|
||||
|
||||
// the atomic values which are arrays are not MongooseArrays. we
|
||||
// need to convert their elements as if they were MongooseArrays
|
||||
// to handle populated arrays versus DocumentArrays properly.
|
||||
if (utils.isMongooseObject(val)) {
|
||||
val = val.toObject(opts);
|
||||
} else if (Array.isArray(val)) {
|
||||
val = this.toObject.call(val, opts);
|
||||
} else if (val != null && Array.isArray(val.$each)) {
|
||||
val.$each = this.toObject.call(val.$each, opts);
|
||||
} else if (val != null && typeof val.valueOf === 'function') {
|
||||
val = val.valueOf();
|
||||
}
|
||||
|
||||
if (op === '$addToSet') {
|
||||
val = {$each: val};
|
||||
}
|
||||
|
||||
ret.push([op, val]);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$atomics() {
|
||||
return this[arrayAtomicsSymbol];
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$parent() {
|
||||
return this[arrayParentSymbol];
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$path() {
|
||||
return this[arrayPathSymbol];
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically shifts the array at most one time per document `save()`.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* _Calling this multiple times on an array before saving sends the same command as calling it once._
|
||||
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
|
||||
*
|
||||
* doc.array = [1,2,3];
|
||||
*
|
||||
* var shifted = doc.array.$shift();
|
||||
* console.log(shifted); // 1
|
||||
* console.log(doc.array); // [2,3]
|
||||
*
|
||||
* // no affect
|
||||
* shifted = doc.array.$shift();
|
||||
* console.log(doc.array); // [2,3]
|
||||
*
|
||||
* doc.save(function (err) {
|
||||
* if (err) return handleError(err);
|
||||
*
|
||||
* // we saved, now $shift works again
|
||||
* shifted = doc.array.$shift();
|
||||
* console.log(shifted ); // 2
|
||||
* console.log(doc.array); // [3]
|
||||
* })
|
||||
*
|
||||
* @api public
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @method $shift
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
|
||||
*/
|
||||
|
||||
$shift() {
|
||||
this._registerAtomic('$pop', -1);
|
||||
this._markModified();
|
||||
|
||||
// only allow shifting once
|
||||
if (this._shifted) {
|
||||
return;
|
||||
}
|
||||
this._shifted = true;
|
||||
|
||||
return [].shift.call(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pops the array atomically at most one time per document `save()`.
|
||||
*
|
||||
* #### NOTE:
|
||||
*
|
||||
* _Calling this mulitple times on an array before saving sends the same command as calling it once._
|
||||
* _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
|
||||
*
|
||||
* doc.array = [1,2,3];
|
||||
*
|
||||
* var popped = doc.array.$pop();
|
||||
* console.log(popped); // 3
|
||||
* console.log(doc.array); // [1,2]
|
||||
*
|
||||
* // no affect
|
||||
* popped = doc.array.$pop();
|
||||
* console.log(doc.array); // [1,2]
|
||||
*
|
||||
* doc.save(function (err) {
|
||||
* if (err) return handleError(err);
|
||||
*
|
||||
* // we saved, now $pop works again
|
||||
* popped = doc.array.$pop();
|
||||
* console.log(popped); // 2
|
||||
* console.log(doc.array); // [1]
|
||||
* })
|
||||
*
|
||||
* @api public
|
||||
* @method $pop
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
|
||||
* @method $pop
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
$pop() {
|
||||
this._registerAtomic('$pop', 1);
|
||||
this._markModified();
|
||||
|
||||
// only allow popping once
|
||||
if (this._popped) {
|
||||
return;
|
||||
}
|
||||
this._popped = true;
|
||||
|
||||
return [].pop.call(this);
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
$schema() {
|
||||
return this[arraySchemaSymbol];
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts a member based on this arrays schema.
|
||||
*
|
||||
* @param {any} value
|
||||
* @return value the casted value
|
||||
* @method _cast
|
||||
* @api private
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_cast(value) {
|
||||
let populated = false;
|
||||
let Model;
|
||||
|
||||
if (this[arrayParentSymbol]) {
|
||||
populated = this[arrayParentSymbol].populated(this[arrayPathSymbol], true);
|
||||
}
|
||||
|
||||
if (populated && value !== null && value !== undefined) {
|
||||
// cast to the populated Models schema
|
||||
Model = populated.options[populateModelSymbol];
|
||||
|
||||
// only objects are permitted so we can safely assume that
|
||||
// non-objects are to be interpreted as _id
|
||||
if (Buffer.isBuffer(value) ||
|
||||
value instanceof ObjectId || !utils.isObject(value)) {
|
||||
value = {_id: value};
|
||||
}
|
||||
|
||||
// gh-2399
|
||||
// we should cast model only when it's not a discriminator
|
||||
const isDisc = value.schema && value.schema.discriminatorMapping &&
|
||||
value.schema.discriminatorMapping.key !== undefined;
|
||||
if (!isDisc) {
|
||||
value = new Model(value);
|
||||
}
|
||||
return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], true);
|
||||
}
|
||||
|
||||
return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal helper for .map()
|
||||
*
|
||||
* @api private
|
||||
* @return {Number}
|
||||
* @method _mapCast
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_mapCast(val, index) {
|
||||
return this._cast(val, this.length + index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks this array as modified.
|
||||
*
|
||||
* If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
|
||||
*
|
||||
* @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array
|
||||
* @param {String} embeddedPath the path which changed in the embeddedDoc
|
||||
* @method _markModified
|
||||
* @api private
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_markModified(elem, embeddedPath) {
|
||||
const parent = this[arrayParentSymbol];
|
||||
let dirtyPath;
|
||||
|
||||
if (parent) {
|
||||
dirtyPath = this[arrayPathSymbol];
|
||||
|
||||
if (arguments.length) {
|
||||
if (embeddedPath != null) {
|
||||
// an embedded doc bubbled up the change
|
||||
dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath;
|
||||
} else {
|
||||
// directly set an index
|
||||
dirtyPath = dirtyPath + '.' + elem;
|
||||
}
|
||||
}
|
||||
|
||||
parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an atomic operation with the parent.
|
||||
*
|
||||
* @param {Array} op operation
|
||||
* @param {any} val
|
||||
* @method _registerAtomic
|
||||
* @api private
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
_registerAtomic(op, val) {
|
||||
if (op === '$set') {
|
||||
// $set takes precedence over all other ops.
|
||||
// mark entire array modified.
|
||||
this[arrayAtomicsSymbol] = {$set: val};
|
||||
cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]);
|
||||
this._markModified();
|
||||
return this;
|
||||
}
|
||||
|
||||
const atomics = this[arrayAtomicsSymbol];
|
||||
|
||||
// reset pop/shift after save
|
||||
if (op === '$pop' && !('$pop' in atomics)) {
|
||||
const _this = this;
|
||||
this[arrayParentSymbol].once('save', function() {
|
||||
_this._popped = _this._shifted = null;
|
||||
});
|
||||
}
|
||||
|
||||
// check for impossible $atomic combos (Mongo denies more than one
|
||||
// $atomic op on a single path
|
||||
if (this[arrayAtomicsSymbol].$set ||
|
||||
Object.keys(atomics).length && !(op in atomics)) {
|
||||
// a different op was previously registered.
|
||||
// save the entire thing.
|
||||
this[arrayAtomicsSymbol] = {$set: this};
|
||||
return this;
|
||||
}
|
||||
|
||||
let selector;
|
||||
|
||||
if (op === '$pullAll' || op === '$addToSet') {
|
||||
atomics[op] || (atomics[op] = []);
|
||||
atomics[op] = atomics[op].concat(val);
|
||||
} else if (op === '$pullDocs') {
|
||||
const pullOp = atomics['$pull'] || (atomics['$pull'] = {});
|
||||
if (val[0] instanceof EmbeddedDocument) {
|
||||
selector = pullOp['$or'] || (pullOp['$or'] = []);
|
||||
Array.prototype.push.apply(selector, val.map(function(v) {
|
||||
return v.toObject({transform: false, virtuals: false});
|
||||
}));
|
||||
} else {
|
||||
selector = pullOp['_id'] || (pullOp['_id'] = {$in: []});
|
||||
selector['$in'] = selector['$in'].concat(val);
|
||||
}
|
||||
} else if (op === '$push') {
|
||||
atomics.$push = atomics.$push || { $each: [] };
|
||||
atomics.$push.$each = atomics.$push.$each.concat(val);
|
||||
} else {
|
||||
atomics[op] = val;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds values to the array if not already present.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* console.log(doc.array) // [2,3,4]
|
||||
* var added = doc.array.addToSet(4,5);
|
||||
* console.log(doc.array) // [2,3,4,5]
|
||||
* console.log(added) // [5]
|
||||
*
|
||||
* @param {any} [args...]
|
||||
* @return {Array} the values that were added
|
||||
* @memberOf MongooseArray
|
||||
* @api public
|
||||
* @method addToSet
|
||||
*/
|
||||
|
||||
addToSet() {
|
||||
_checkManualPopulation(this, arguments);
|
||||
|
||||
let values = [].map.call(arguments, this._mapCast, this);
|
||||
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
|
||||
const added = [];
|
||||
let type = '';
|
||||
if (values[0] instanceof EmbeddedDocument) {
|
||||
type = 'doc';
|
||||
} else if (values[0] instanceof Date) {
|
||||
type = 'date';
|
||||
}
|
||||
|
||||
values.forEach(function(v) {
|
||||
let found;
|
||||
const val = +v;
|
||||
switch (type) {
|
||||
case 'doc':
|
||||
found = this.some(function(doc) {
|
||||
return doc.equals(v);
|
||||
});
|
||||
break;
|
||||
case 'date':
|
||||
found = this.some(function(d) {
|
||||
return +d === val;
|
||||
});
|
||||
break;
|
||||
default:
|
||||
found = ~this.indexOf(v);
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
[].push.call(this, v);
|
||||
this._registerAtomic('$addToSet', v);
|
||||
this._markModified();
|
||||
[].push.call(added, v);
|
||||
}
|
||||
}, this);
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of pending atomic operations to send to the db for this array.
|
||||
*
|
||||
* @api private
|
||||
* @return {Number}
|
||||
* @method hasAtomics
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
hasAtomics() {
|
||||
if (!utils.isPOJO(this[arrayAtomicsSymbol])) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Object.keys(this[arrayAtomicsSymbol]).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether or not the `obj` is included in the array.
|
||||
*
|
||||
* @param {Object} obj the item to check
|
||||
* @return {Boolean}
|
||||
* @api public
|
||||
* @method includes
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
includes(obj) {
|
||||
return this.indexOf(obj) !== -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the index of `obj` or `-1` if not found.
|
||||
*
|
||||
* @param {Object} obj the item to look for
|
||||
* @return {Number}
|
||||
* @api public
|
||||
* @method indexOf
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
indexOf(obj) {
|
||||
if (obj instanceof ObjectId) {
|
||||
obj = obj.toString();
|
||||
}
|
||||
for (let i = 0, len = this.length; i < len; ++i) {
|
||||
if (obj == this[i]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for console.log
|
||||
*
|
||||
* @api public
|
||||
* @method inspect
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
inspect() {
|
||||
return JSON.stringify(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes items to the array non-atomically.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @param {any} [args...]
|
||||
* @api public
|
||||
* @method nonAtomicPush
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
nonAtomicPush() {
|
||||
const values = [].map.call(arguments, this._mapCast, this);
|
||||
const ret = [].push.apply(this, values);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @see MongooseArray#$pop #types_array_MongooseArray-%24pop
|
||||
* @api public
|
||||
* @method pop
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
pop() {
|
||||
const ret = [].pop.call(this);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls items from the array atomically. Equality is determined by casting
|
||||
* the provided value to an embedded document and comparing using
|
||||
* [the `Document.equals()` function.](./api.html#document_Document-equals)
|
||||
*
|
||||
* ####Examples:
|
||||
*
|
||||
* doc.array.pull(ObjectId)
|
||||
* doc.array.pull({ _id: 'someId' })
|
||||
* doc.array.pull(36)
|
||||
* doc.array.pull('tag 1', 'tag 2')
|
||||
*
|
||||
* To remove a document from a subdocument array we may pass an object with a matching `_id`.
|
||||
*
|
||||
* doc.subdocs.push({ _id: 4815162342 })
|
||||
* doc.subdocs.pull({ _id: 4815162342 }) // removed
|
||||
*
|
||||
* Or we may passing the _id directly and let mongoose take care of it.
|
||||
*
|
||||
* doc.subdocs.push({ _id: 4815162342 })
|
||||
* doc.subdocs.pull(4815162342); // works
|
||||
*
|
||||
* The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.
|
||||
*
|
||||
* @param {any} [args...]
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
|
||||
* @api public
|
||||
* @method pull
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
pull() {
|
||||
const values = [].map.call(arguments, this._cast, this);
|
||||
const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]);
|
||||
let i = cur.length;
|
||||
let mem;
|
||||
|
||||
while (i--) {
|
||||
mem = cur[i];
|
||||
if (mem instanceof Document) {
|
||||
const some = values.some(function(v) {
|
||||
return mem.equals(v);
|
||||
});
|
||||
if (some) {
|
||||
[].splice.call(cur, i, 1);
|
||||
}
|
||||
} else if (~cur.indexOf.call(values, mem)) {
|
||||
[].splice.call(cur, i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (values[0] instanceof EmbeddedDocument) {
|
||||
this._registerAtomic('$pullDocs', values.map(function(v) {
|
||||
return v._id || v;
|
||||
}));
|
||||
} else {
|
||||
this._registerAtomic('$pullAll', values);
|
||||
}
|
||||
|
||||
this._markModified();
|
||||
|
||||
// Might have modified child paths and then pulled, like
|
||||
// `doc.children[1].name = 'test';` followed by
|
||||
// `doc.children.remove(doc.children[0]);`. In this case we fall back
|
||||
// to a `$set` on the whole array. See #3511
|
||||
if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) {
|
||||
this._registerAtomic('$set', this);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
|
||||
*
|
||||
* @param {Object} [args...]
|
||||
* @api public
|
||||
* @method push
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
push() {
|
||||
if (this[arraySchemaSymbol] == null) {
|
||||
return _basePush.apply(this, arguments);
|
||||
}
|
||||
|
||||
_checkManualPopulation(this, arguments);
|
||||
|
||||
let values = [].map.call(arguments, this._mapCast, this);
|
||||
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol], undefined,
|
||||
undefined, { skipDocumentArrayCast: true });
|
||||
const ret = [].push.apply(this, values);
|
||||
|
||||
this._registerAtomic('$push', values);
|
||||
this._markModified();
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias of [pull](#types_array_MongooseArray-pull)
|
||||
*
|
||||
* @see MongooseArray#pull #types_array_MongooseArray-pull
|
||||
* @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
|
||||
* @api public
|
||||
* @memberOf MongooseArray
|
||||
* @instance
|
||||
* @method remove
|
||||
*/
|
||||
|
||||
remove() {
|
||||
return this.pull.apply(this, arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the casted `val` at index `i` and marks the array modified.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* // given documents based on the following
|
||||
* var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
|
||||
*
|
||||
* var doc = new Doc({ array: [2,3,4] })
|
||||
*
|
||||
* console.log(doc.array) // [2,3,4]
|
||||
*
|
||||
* doc.array.set(1,"5");
|
||||
* console.log(doc.array); // [2,5,4] // properly cast to number
|
||||
* doc.save() // the change is saved
|
||||
*
|
||||
* // VS not using array#set
|
||||
* doc.array[1] = "5";
|
||||
* console.log(doc.array); // [2,"5",4] // no casting
|
||||
* doc.save() // change is not saved
|
||||
*
|
||||
* @return {Array} this
|
||||
* @api public
|
||||
* @method set
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
set(i, val) {
|
||||
const value = this._cast(val, i);
|
||||
this[i] = value;
|
||||
this._markModified(i);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* doc.array = [2,3];
|
||||
* var res = doc.array.shift();
|
||||
* console.log(res) // 2
|
||||
* console.log(doc.array) // [3]
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method shift
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
shift() {
|
||||
const ret = [].shift.call(this);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
|
||||
*
|
||||
* ####NOTE:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method sort
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
sort() {
|
||||
const ret = [].sort.apply(this, arguments);
|
||||
this._registerAtomic('$set', this);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method splice
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
splice() {
|
||||
let ret;
|
||||
|
||||
_checkManualPopulation(this, Array.prototype.slice.call(arguments, 2));
|
||||
|
||||
if (arguments.length) {
|
||||
const vals = [];
|
||||
for (let i = 0; i < arguments.length; ++i) {
|
||||
vals[i] = i < 2 ?
|
||||
arguments[i] :
|
||||
this._cast(arguments[i], arguments[0] + (i - 2));
|
||||
}
|
||||
ret = [].splice.apply(this, vals);
|
||||
this._registerAtomic('$set', this);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
toBSON() {
|
||||
return this.toObject(internalToObjectOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a native js Array.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {Array}
|
||||
* @api public
|
||||
* @method toObject
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
toObject(options) {
|
||||
if (options && options.depopulate) {
|
||||
options = utils.clone(options);
|
||||
options._isNested = true;
|
||||
return this.map(function(doc) {
|
||||
return doc instanceof Document
|
||||
? doc.toObject(options)
|
||||
: doc;
|
||||
});
|
||||
}
|
||||
|
||||
return this.slice();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
|
||||
*
|
||||
* ####Note:
|
||||
*
|
||||
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
|
||||
*
|
||||
* @api public
|
||||
* @method unshift
|
||||
* @memberOf MongooseArray
|
||||
*/
|
||||
|
||||
unshift() {
|
||||
_checkManualPopulation(this, arguments);
|
||||
|
||||
let values = [].map.call(arguments, this._cast, this);
|
||||
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
|
||||
[].unshift.apply(this, values);
|
||||
this._registerAtomic('$set', this);
|
||||
this._markModified();
|
||||
return this.length;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CoreMongooseArray;
|
||||
if (util.inspect.custom) {
|
||||
CoreMongooseArray.prototype[util.inspect.custom] =
|
||||
CoreMongooseArray.prototype.inspect;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function _isAllSubdocs(docs, ref) {
|
||||
if (!ref) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < docs.length; ++i) {
|
||||
const arg = docs[i];
|
||||
if (arg == null) {
|
||||
return false;
|
||||
}
|
||||
const model = arg.constructor;
|
||||
if (!(arg instanceof Document) ||
|
||||
(model.modelName !== ref && model.baseModelName !== ref)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
function _checkManualPopulation(arr, docs) {
|
||||
const ref = arr == null ?
|
||||
null :
|
||||
get(arr[arraySchemaSymbol], 'caster.options.ref', null);
|
||||
if (arr.length === 0 &&
|
||||
docs.length > 0) {
|
||||
if (_isAllSubdocs(docs, ref)) {
|
||||
arr[arrayParentSymbol].populated(arr[arrayPathSymbol], [], {
|
||||
[populateModelSymbol]: docs[0].constructor
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CoreMongooseArray;
|
||||
|
||||
+4
-11
@@ -6,7 +6,6 @@
|
||||
|
||||
const CoreMongooseArray = require('./core_array');
|
||||
const Document = require('../document');
|
||||
const MongooseArray = require('./array');
|
||||
const ObjectId = require('./objectid');
|
||||
const castObjectId = require('../cast/objectid');
|
||||
const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;
|
||||
@@ -20,6 +19,8 @@ const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
|
||||
const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol;
|
||||
const documentArrayParent = require('../helpers/symbols').documentArrayParent;
|
||||
|
||||
const _basePush = Array.prototype.push;
|
||||
|
||||
/**
|
||||
* DocumentArray constructor
|
||||
*
|
||||
@@ -52,21 +53,13 @@ function MongooseDocumentArray(values, path, doc) {
|
||||
arr[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]);
|
||||
}
|
||||
values.forEach(v => {
|
||||
arr.push(v);
|
||||
_basePush.call(arr, v);
|
||||
});
|
||||
}
|
||||
arr[arrayPathSymbol] = path;
|
||||
|
||||
// Values always have to be passed to the constructor to initialize, since
|
||||
// otherwise MongooseArray#push will mark the array as modified to the parent.
|
||||
const keysMA = Object.keys(MongooseArray.mixin);
|
||||
let numKeys = keysMA.length;
|
||||
for (let j = 0; j < numKeys; ++j) {
|
||||
arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]];
|
||||
}
|
||||
|
||||
const keysMDA = Object.keys(MongooseDocumentArray.mixin);
|
||||
numKeys = keysMDA.length;
|
||||
let numKeys = keysMDA.length;
|
||||
for (let i = 0; i < numKeys; ++i) {
|
||||
arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]];
|
||||
}
|
||||
|
||||
+3
-1
@@ -5,6 +5,8 @@ const get = require('../helpers/get');
|
||||
const util = require('util');
|
||||
const utils = require('../utils');
|
||||
|
||||
const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
@@ -57,7 +59,7 @@ class MongooseMap extends Map {
|
||||
|
||||
if (populated != null) {
|
||||
if (value.$__ == null) {
|
||||
value = new populated.options.model(value);
|
||||
value = new populated.options[populateModelSymbol](value);
|
||||
}
|
||||
value.$__.wasPopulated = true;
|
||||
} else {
|
||||
|
||||
+147
-85
@@ -6,6 +6,7 @@
|
||||
|
||||
const Decimal = require('./types/decimal128');
|
||||
const ObjectId = require('./types/objectid');
|
||||
const PopulateOptions = require('./options/PopulateOptions');
|
||||
const PromiseProvider = require('./promise_provider');
|
||||
const cloneRegExp = require('regexp-clone');
|
||||
const get = require('./helpers/get');
|
||||
@@ -391,7 +392,11 @@ exports.merge = function merge(to, from, options, path) {
|
||||
}
|
||||
if (from[key] != null) {
|
||||
if (from[key].instanceOfSchema) {
|
||||
to[key] = from[key].clone();
|
||||
if (to[key].instanceOfSchema) {
|
||||
to[key].add(from[key].clone());
|
||||
} else {
|
||||
to[key] = from[key].clone();
|
||||
}
|
||||
continue;
|
||||
} else if (from[key] instanceof ObjectId) {
|
||||
to[key] = new ObjectId(from[key]);
|
||||
@@ -478,7 +483,7 @@ exports.isObject = function(arg) {
|
||||
* @return {Boolean}
|
||||
*/
|
||||
|
||||
exports.isPOJO = function(arg) {
|
||||
exports.isPOJO = function isPOJO(arg) {
|
||||
if (arg == null || typeof arg !== 'object') {
|
||||
return false;
|
||||
}
|
||||
@@ -489,6 +494,37 @@ exports.isPOJO = function(arg) {
|
||||
return !proto || proto.constructor.name === 'Object';
|
||||
};
|
||||
|
||||
/*!
|
||||
* Determines if `obj` is a built-in object like an array, date, boolean,
|
||||
* etc.
|
||||
*/
|
||||
|
||||
exports.isNativeObject = function(arg) {
|
||||
return Array.isArray(arg) ||
|
||||
arg instanceof Date ||
|
||||
arg instanceof Boolean ||
|
||||
arg instanceof Number ||
|
||||
arg instanceof String;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Search if `obj` or any POJOs nested underneath `obj` has a property named
|
||||
* `key`
|
||||
*/
|
||||
|
||||
exports.hasKey = function hasKey(obj, key) {
|
||||
const props = Object.keys(obj);
|
||||
for (const prop of props) {
|
||||
if (prop === key) {
|
||||
return true;
|
||||
}
|
||||
if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/*!
|
||||
* A faster Array.prototype.slice.call(arguments) alternative
|
||||
* @api private
|
||||
@@ -575,39 +611,54 @@ exports.expires = function expires(object) {
|
||||
delete object.expires;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Populate options constructor
|
||||
*/
|
||||
|
||||
function PopulateOptions(obj) {
|
||||
this.path = obj.path;
|
||||
this.match = obj.match;
|
||||
this.select = obj.select;
|
||||
this.options = obj.options;
|
||||
this.model = obj.model;
|
||||
if (typeof obj.subPopulate === 'object') {
|
||||
this.populate = obj.subPopulate;
|
||||
}
|
||||
if (obj.justOne != null) {
|
||||
this.justOne = obj.justOne;
|
||||
}
|
||||
if (obj.count != null) {
|
||||
this.count = obj.count;
|
||||
}
|
||||
this._docs = {};
|
||||
}
|
||||
|
||||
// make it compatible with utils.clone
|
||||
PopulateOptions.prototype.constructor = Object;
|
||||
|
||||
// expose
|
||||
exports.PopulateOptions = PopulateOptions;
|
||||
|
||||
/*!
|
||||
* populate helper
|
||||
*/
|
||||
|
||||
exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) {
|
||||
// might have passed an object specifying all arguments
|
||||
let obj = null;
|
||||
if (arguments.length === 1) {
|
||||
if (path instanceof PopulateOptions) {
|
||||
return [path];
|
||||
}
|
||||
|
||||
if (Array.isArray(path)) {
|
||||
const singles = makeSingles(path);
|
||||
return singles.map(o => exports.populate(o)[0]);
|
||||
}
|
||||
|
||||
if (exports.isObject(path)) {
|
||||
obj = Object.assign({}, path);
|
||||
} else {
|
||||
obj = { path: path };
|
||||
}
|
||||
} else if (typeof model === 'object') {
|
||||
obj = {
|
||||
path: path,
|
||||
select: select,
|
||||
match: model,
|
||||
options: match
|
||||
};
|
||||
} else {
|
||||
obj = {
|
||||
path: path,
|
||||
select: select,
|
||||
model: model,
|
||||
match: match,
|
||||
options: options,
|
||||
populate: subPopulate,
|
||||
justOne: justOne,
|
||||
count: count
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof obj.path !== 'string') {
|
||||
throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
|
||||
}
|
||||
|
||||
return _populateObj(obj);
|
||||
|
||||
// The order of select/conditions args is opposite Model.find but
|
||||
// necessary to keep backward compatibility (select could be
|
||||
// an array, string, or object literal).
|
||||
@@ -628,47 +679,12 @@ exports.populate = function populate(path, select, model, match, options, subPop
|
||||
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
// might have passed an object specifying all arguments
|
||||
if (arguments.length === 1) {
|
||||
if (path instanceof PopulateOptions) {
|
||||
return [path];
|
||||
}
|
||||
|
||||
if (Array.isArray(path)) {
|
||||
const singles = makeSingles(path);
|
||||
return singles.map(function(o) {
|
||||
if (o.populate && !(o.match || o.options)) {
|
||||
return exports.populate(o)[0];
|
||||
} else {
|
||||
return exports.populate(o)[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (exports.isObject(path)) {
|
||||
match = path.match;
|
||||
options = path.options;
|
||||
select = path.select;
|
||||
model = path.model;
|
||||
subPopulate = path.populate;
|
||||
justOne = path.justOne;
|
||||
path = path.path;
|
||||
count = path.count;
|
||||
}
|
||||
} else if (typeof model === 'object') {
|
||||
options = match;
|
||||
match = model;
|
||||
model = undefined;
|
||||
}
|
||||
|
||||
if (typeof path !== 'string') {
|
||||
throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
|
||||
}
|
||||
|
||||
if (Array.isArray(subPopulate)) {
|
||||
function _populateObj(obj) {
|
||||
if (Array.isArray(obj.populate)) {
|
||||
const ret = [];
|
||||
subPopulate.forEach(function(obj) {
|
||||
obj.populate.forEach(function(obj) {
|
||||
if (/[\s]/.test(obj.path)) {
|
||||
const copy = Object.assign({}, obj);
|
||||
const paths = copy.path.split(' ');
|
||||
@@ -680,29 +696,23 @@ exports.populate = function populate(path, select, model, match, options, subPop
|
||||
ret.push(exports.populate(obj)[0]);
|
||||
}
|
||||
});
|
||||
subPopulate = exports.populate(ret);
|
||||
} else if (typeof subPopulate === 'object') {
|
||||
subPopulate = exports.populate(subPopulate);
|
||||
obj.populate = exports.populate(ret);
|
||||
} else if (obj.populate != null && typeof obj.populate === 'object') {
|
||||
obj.populate = exports.populate(obj.populate);
|
||||
}
|
||||
|
||||
const ret = [];
|
||||
const paths = path.split(' ');
|
||||
options = exports.clone(options);
|
||||
const paths = obj.path.split(' ');
|
||||
if (obj.options != null) {
|
||||
obj.options = exports.clone(obj.options);
|
||||
}
|
||||
|
||||
for (let i = 0; i < paths.length; ++i) {
|
||||
ret.push(new PopulateOptions({
|
||||
path: paths[i],
|
||||
select: select,
|
||||
match: match,
|
||||
options: options,
|
||||
model: model,
|
||||
subPopulate: subPopulate,
|
||||
justOne: justOne,
|
||||
count: count
|
||||
}));
|
||||
ret.push(new PopulateOptions(Object.assign({}, obj, { path: paths[i] })));
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
/*!
|
||||
* Return the value of `obj` at the given `path`.
|
||||
@@ -809,6 +819,58 @@ exports.array.flatten = function flatten(arr, filter, ret) {
|
||||
return ret;
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
const _hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
|
||||
exports.hasUserDefinedProperty = function(obj, key) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Array.isArray(key)) {
|
||||
for (const k of key) {
|
||||
if (exports.hasUserDefinedProperty(obj, k)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_hasOwnProperty.call(obj, key)) {
|
||||
return true;
|
||||
}
|
||||
if (key in obj) {
|
||||
const v = obj[key];
|
||||
return v !== Object.prototype[key] && v !== Array.prototype[key];
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/*!
|
||||
* ignore
|
||||
*/
|
||||
|
||||
const MAX_ARRAY_INDEX = Math.pow(2, 32) - 1;
|
||||
|
||||
exports.isArrayIndex = function(val) {
|
||||
if (typeof val === 'number') {
|
||||
return val >= 0 && val <= MAX_ARRAY_INDEX;
|
||||
}
|
||||
if (typeof val === 'string') {
|
||||
if (!/^\d+$/.test(val)) {
|
||||
return false;
|
||||
}
|
||||
val = +val;
|
||||
return val >= 0 && val <= MAX_ARRAY_INDEX;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/*!
|
||||
* Removes duplicate values from an array
|
||||
*
|
||||
|
||||
+35
-16
@@ -62,16 +62,22 @@ VirtualType.prototype.clone = function() {
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines a getter.
|
||||
* Adds a custom getter to this virtual.
|
||||
*
|
||||
* Mongoose calls the getter function with 3 parameters:
|
||||
*
|
||||
* - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`.
|
||||
* - `virtual`: the virtual object you called `.get()` on
|
||||
* - `doc`: the document this virtual is attached to. Equivalent to `this`.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var virtual = schema.virtual('fullname');
|
||||
* virtual.get(function () {
|
||||
* virtual.get(function(value, virtual, doc) {
|
||||
* return this.name.first + ' ' + this.name.last;
|
||||
* });
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @param {Function(Any, VirtualType, Document)} fn
|
||||
* @return {VirtualType} this
|
||||
* @api public
|
||||
*/
|
||||
@@ -82,18 +88,31 @@ VirtualType.prototype.get = function(fn) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines a setter.
|
||||
* Adds a custom setter to this virtual.
|
||||
*
|
||||
* Mongoose calls the setter function with 3 parameters:
|
||||
*
|
||||
* - `value`: the value being set
|
||||
* - `virtual`: the virtual object you're calling `.set()` on
|
||||
* - `doc`: the document this virtual is attached to. Equivalent to `this`.
|
||||
*
|
||||
* ####Example:
|
||||
*
|
||||
* var virtual = schema.virtual('fullname');
|
||||
* virtual.set(function (v) {
|
||||
* var parts = v.split(' ');
|
||||
* const virtual = schema.virtual('fullname');
|
||||
* virtual.set(function(value, virtual, doc) {
|
||||
* var parts = value.split(' ');
|
||||
* this.name.first = parts[0];
|
||||
* this.name.last = parts[1];
|
||||
* });
|
||||
*
|
||||
* @param {Function} fn
|
||||
* const Model = mongoose.model('Test', schema);
|
||||
* const doc = new Model();
|
||||
* // Calls the setter with `value = 'Jean-Luc Picard'`
|
||||
* doc.fullname = 'Jean-Luc Picard';
|
||||
* doc.name.first; // 'Jean-Luc'
|
||||
* doc.name.last; // 'Picard'
|
||||
*
|
||||
* @param {Function(Any, VirtualType, Document)} fn
|
||||
* @return {VirtualType} this
|
||||
* @api public
|
||||
*/
|
||||
@@ -104,35 +123,35 @@ VirtualType.prototype.set = function(fn) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies getters to `value` using optional `scope`.
|
||||
* Applies getters to `value`.
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Object} scope
|
||||
* @param {Document} doc The document this virtual is attached to
|
||||
* @return {any} the value after applying all getters
|
||||
* @api public
|
||||
*/
|
||||
|
||||
VirtualType.prototype.applyGetters = function(value, scope) {
|
||||
VirtualType.prototype.applyGetters = function(value, doc) {
|
||||
let v = value;
|
||||
for (let l = this.getters.length - 1; l >= 0; l--) {
|
||||
v = this.getters[l].call(scope, v, this);
|
||||
v = this.getters[l].call(doc, v, this, doc);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies setters to `value` using optional `scope`.
|
||||
* Applies setters to `value`.
|
||||
*
|
||||
* @param {Object} value
|
||||
* @param {Object} scope
|
||||
* @param {Document} doc
|
||||
* @return {any} the value after applying all setters
|
||||
* @api public
|
||||
*/
|
||||
|
||||
VirtualType.prototype.applySetters = function(value, scope) {
|
||||
VirtualType.prototype.applySetters = function(value, doc) {
|
||||
let v = value;
|
||||
for (let l = this.setters.length - 1; l >= 0; l--) {
|
||||
v = this.setters[l].call(scope, v, this);
|
||||
v = this.setters[l].call(doc, v, this, doc);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
-268
@@ -1,268 +0,0 @@
|
||||
<a name="1.1.1"></a>
|
||||
## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba))
|
||||
|
||||
|
||||
|
||||
<a name="1.1.0"></a>
|
||||
# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141))
|
||||
|
||||
|
||||
|
||||
<a name="1.0.9"></a>
|
||||
## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f))
|
||||
|
||||
|
||||
|
||||
<a name="1.0.7"></a>
|
||||
## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5))
|
||||
* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b))
|
||||
* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c))
|
||||
* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10))
|
||||
|
||||
|
||||
|
||||
<a name="1.0.6"></a>
|
||||
## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc))
|
||||
|
||||
|
||||
|
||||
<a name="1.0.5"></a>
|
||||
## 1.0.5 (2018-02-26)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45))
|
||||
* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6))
|
||||
|
||||
|
||||
|
||||
1.0.4 2016-01-11
|
||||
----------------
|
||||
- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases.
|
||||
|
||||
1.0.3 2016-01-03
|
||||
----------------
|
||||
- Fixed toString for ObjectId so it will work with inspect.
|
||||
|
||||
1.0.2 2016-01-02
|
||||
----------------
|
||||
- Minor optimizations for ObjectID to use Buffer.from where available.
|
||||
|
||||
1.0.1 2016-12-06
|
||||
----------------
|
||||
- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons.
|
||||
|
||||
1.0.0 2016-12-06
|
||||
----------------
|
||||
- Introduced new BSON API and documentation.
|
||||
|
||||
0.5.7 2016-11-18
|
||||
-----------------
|
||||
- NODE-848 BSON Regex flags must be alphabetically ordered.
|
||||
|
||||
0.5.6 2016-10-19
|
||||
-----------------
|
||||
- NODE-833, Detects cyclic dependencies in documents and throws error if one is found.
|
||||
- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke).
|
||||
|
||||
0.5.5 2016-09-15
|
||||
-----------------
|
||||
- Added DBPointer up conversion to DBRef
|
||||
|
||||
0.5.4 2016-08-23
|
||||
-----------------
|
||||
- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only.
|
||||
|
||||
0.5.3 2016-07-11
|
||||
-----------------
|
||||
- Throw error if ObjectId is not a string or a buffer.
|
||||
|
||||
0.5.2 2016-07-11
|
||||
-----------------
|
||||
- All values encoded big-endian style for ObjectId.
|
||||
|
||||
0.5.1 2016-07-11
|
||||
-----------------
|
||||
- Fixed encoding/decoding issue in ObjectId timestamp generation.
|
||||
- Removed BinaryParser dependency from the serializer/deserializer.
|
||||
|
||||
0.5.0 2016-07-05
|
||||
-----------------
|
||||
- Added Decimal128 type and extended test suite to include entire bson corpus.
|
||||
|
||||
0.4.23 2016-04-08
|
||||
-----------------
|
||||
- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries.
|
||||
- Remove one package from dependency due to having been pulled from NPM.
|
||||
|
||||
0.4.22 2016-03-04
|
||||
-----------------
|
||||
- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas).
|
||||
- Fixed issue with undefined type on deserializing.
|
||||
|
||||
0.4.21 2016-01-12
|
||||
-----------------
|
||||
- Minor optimizations to avoid non needed object creation.
|
||||
|
||||
0.4.20 2015-10-15
|
||||
-----------------
|
||||
- Added bower file to repository.
|
||||
- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed)
|
||||
|
||||
0.4.19 2015-10-15
|
||||
-----------------
|
||||
- Remove all support for bson-ext.
|
||||
|
||||
0.4.18 2015-10-15
|
||||
-----------------
|
||||
- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139
|
||||
- add option for deserializing binary into Buffer object #116
|
||||
|
||||
0.4.17 2015-10-15
|
||||
-----------------
|
||||
- Validate regexp string for null bytes and throw if there is one.
|
||||
|
||||
0.4.16 2015-10-07
|
||||
-----------------
|
||||
- Fixed issue with return statement in Map.js.
|
||||
|
||||
0.4.15 2015-10-06
|
||||
-----------------
|
||||
- Exposed Map correctly via index.js file.
|
||||
|
||||
0.4.14 2015-10-06
|
||||
-----------------
|
||||
- Exposed Map correctly via bson.js file.
|
||||
|
||||
0.4.13 2015-10-06
|
||||
-----------------
|
||||
- Added ES6 Map type serialization as well as a polyfill for ES5.
|
||||
|
||||
0.4.12 2015-09-18
|
||||
-----------------
|
||||
- Made ignore undefined an optional parameter.
|
||||
|
||||
0.4.11 2015-08-06
|
||||
-----------------
|
||||
- Minor fix for invalid key checking.
|
||||
|
||||
0.4.10 2015-08-06
|
||||
-----------------
|
||||
- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type.
|
||||
- Some performance improvements by in lining code.
|
||||
|
||||
0.4.9 2015-08-06
|
||||
----------------
|
||||
- Undefined fields are omitted from serialization in objects.
|
||||
|
||||
0.4.8 2015-07-14
|
||||
----------------
|
||||
- Fixed size validation to ensure we can deserialize from dumped files.
|
||||
|
||||
0.4.7 2015-06-26
|
||||
----------------
|
||||
- Added ability to instruct deserializer to return raw BSON buffers for named array fields.
|
||||
- Minor deserialization optimization by moving inlined function out.
|
||||
|
||||
0.4.6 2015-06-17
|
||||
----------------
|
||||
- Fixed serializeWithBufferAndIndex bug.
|
||||
|
||||
0.4.5 2015-06-17
|
||||
----------------
|
||||
- Removed any references to the shared buffer to avoid non GC collectible bson instances.
|
||||
|
||||
0.4.4 2015-06-17
|
||||
----------------
|
||||
- Fixed rethrowing of error when not RangeError.
|
||||
|
||||
0.4.3 2015-06-17
|
||||
----------------
|
||||
- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed.
|
||||
|
||||
0.4.2 2015-06-16
|
||||
----------------
|
||||
- More fixes for corrupt Bson
|
||||
|
||||
0.4.1 2015-06-16
|
||||
----------------
|
||||
- More fixes for corrupt Bson
|
||||
|
||||
0.4.0 2015-06-16
|
||||
----------------
|
||||
- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser.
|
||||
- Removed bson-ext extension dependency for now.
|
||||
|
||||
0.3.2 2015-03-27
|
||||
----------------
|
||||
- Removed node-gyp from install script in package.json.
|
||||
|
||||
0.3.1 2015-03-27
|
||||
----------------
|
||||
- Return pure js version on native() call if failed to initialize.
|
||||
|
||||
0.3.0 2015-03-26
|
||||
----------------
|
||||
- Pulled out all C++ code into bson-ext and made it an optional dependency.
|
||||
|
||||
0.2.21 2015-03-21
|
||||
-----------------
|
||||
- Updated Nan to 1.7.0 to support io.js and node 0.12.0
|
||||
|
||||
0.2.19 2015-02-16
|
||||
-----------------
|
||||
- Updated Nan to 1.6.2 to support io.js and node 0.12.0
|
||||
|
||||
0.2.18 2015-01-20
|
||||
-----------------
|
||||
- Updated Nan to 1.5.1 to support io.js
|
||||
|
||||
0.2.16 2014-12-17
|
||||
-----------------
|
||||
- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's
|
||||
|
||||
0.2.12 2014-08-24
|
||||
-----------------
|
||||
- Fixes for fortify review of c++ extension
|
||||
- toBSON correctly allows returns of non objects
|
||||
|
||||
0.2.3 2013-10-01
|
||||
----------------
|
||||
- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip)
|
||||
- Fixed issue where corrupt CString's could cause endless loop
|
||||
- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa)
|
||||
|
||||
0.1.4 2012-09-25
|
||||
----------------
|
||||
- Added precompiled c++ native extensions for win32 ia32 and x64
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-170
@@ -1,170 +0,0 @@
|
||||
# BSON parser
|
||||
|
||||
BSON is short for Binary JSON and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org).
|
||||
|
||||
This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory.
|
||||
|
||||
This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext).
|
||||
|
||||
## Usage
|
||||
|
||||
To build a new version perform the following operations:
|
||||
|
||||
```
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
A simple example of how to use BSON in the browser:
|
||||
|
||||
```html
|
||||
<script src="./browser_build/bson.js"></script>
|
||||
|
||||
<script>
|
||||
function start() {
|
||||
// Get the Long type
|
||||
var Long = BSON.Long;
|
||||
// Create a bson parser instance
|
||||
var bson = new BSON();
|
||||
|
||||
// Serialize document
|
||||
var doc = { long: Long.fromNumber(100) }
|
||||
|
||||
// Serialize a document
|
||||
var data = bson.serialize(doc)
|
||||
// De serialize it again
|
||||
var doc_2 = bson.deserialize(data)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
A simple example of how to use BSON in `Node.js`:
|
||||
|
||||
```js
|
||||
// Get BSON parser class
|
||||
var BSON = require('bson')
|
||||
// Get the Long type
|
||||
var Long = BSON.Long;
|
||||
// Create a bson parser instance
|
||||
var bson = new BSON();
|
||||
|
||||
// Serialize document
|
||||
var doc = { long: Long.fromNumber(100) }
|
||||
|
||||
// Serialize a document
|
||||
var data = bson.serialize(doc)
|
||||
console.log('data:', data)
|
||||
|
||||
// Deserialize the resulting Buffer
|
||||
var doc_2 = bson.deserialize(data)
|
||||
console.log('doc_2:', doc_2)
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
`npm install bson`
|
||||
|
||||
## API
|
||||
|
||||
### BSON types
|
||||
|
||||
For all BSON types documentation, please refer to the following sources:
|
||||
* [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/)
|
||||
* [BSON Spec](https://bsonspec.org/)
|
||||
|
||||
### BSON serialization and deserialiation
|
||||
|
||||
**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON.
|
||||
|
||||
#### BSON.serialize
|
||||
|
||||
The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer.
|
||||
|
||||
* `BSON.serialize(object, options)`
|
||||
* @param {Object} object the JavaScript object to serialize.
|
||||
* @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid.
|
||||
* @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions.
|
||||
* @param {Boolean} [options.ignoreUndefined=true]
|
||||
* @return {Buffer} returns a Buffer instance.
|
||||
|
||||
#### BSON.serializeWithBufferAndIndex
|
||||
|
||||
The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer.
|
||||
|
||||
* `BSON.serializeWithBufferAndIndex(object, buffer, options)`
|
||||
* @param {Object} object the JavaScript object to serialize.
|
||||
* @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
|
||||
* @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid.
|
||||
* @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions.
|
||||
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields.
|
||||
* @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into.
|
||||
* @return {Number} returns the index pointing to the last written byte in the buffer.
|
||||
|
||||
#### BSON.calculateObjectSize
|
||||
|
||||
The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object.
|
||||
|
||||
* `BSON.calculateObjectSize(object, options)`
|
||||
* @param {Object} object the JavaScript object to serialize.
|
||||
* @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions.
|
||||
* @param {Boolean} [options.ignoreUndefined=true]
|
||||
* @return {Buffer} returns a Buffer instance.
|
||||
|
||||
#### BSON.deserialize
|
||||
|
||||
The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object.
|
||||
|
||||
* `BSON.deserialize(buffer, options)`
|
||||
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
|
||||
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
|
||||
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
|
||||
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
|
||||
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance.
|
||||
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
|
||||
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
|
||||
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
|
||||
* @return {Object} returns the deserialized Javascript Object.
|
||||
|
||||
#### BSON.deserializeStream
|
||||
|
||||
The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents.
|
||||
|
||||
* `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)`
|
||||
* @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
|
||||
* @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
|
||||
* @param {Number} numberOfDocuments number of documents to deserialize.
|
||||
* @param {Array} documents an array where to store the deserialized documents.
|
||||
* @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
|
||||
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
|
||||
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
|
||||
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
|
||||
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
|
||||
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance.
|
||||
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
|
||||
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
|
||||
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
|
||||
* @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.
|
||||
|
||||
## FAQ
|
||||
|
||||
#### Why does `undefined` get converted to `null`?
|
||||
|
||||
The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys.
|
||||
|
||||
#### How do I add custom serialization logic?
|
||||
|
||||
This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize.
|
||||
|
||||
```javascript
|
||||
var bson = new BSON();
|
||||
|
||||
class CustomSerialize {
|
||||
toBSON() {
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
|
||||
const obj = { answer: new CustomSerialize() };
|
||||
// "{ answer: 42 }"
|
||||
console.log(bson.deserialize(bson.serialize(obj)));
|
||||
```
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"name": "bson",
|
||||
"description": "A bson parser for node.js and the browser",
|
||||
"keywords": [
|
||||
"mongodb",
|
||||
"bson",
|
||||
"parser"
|
||||
],
|
||||
"author": "Christian Amor Kvalheim <christkv@gmail.com>",
|
||||
"main": "./browser_build/bson.js",
|
||||
"license": "Apache-2.0",
|
||||
"moduleType": [
|
||||
"globals",
|
||||
"node"
|
||||
],
|
||||
"ignore": [
|
||||
"**/.*",
|
||||
"alternate_parsers",
|
||||
"benchmarks",
|
||||
"bower_components",
|
||||
"node_modules",
|
||||
"test",
|
||||
"tools"
|
||||
]
|
||||
}
|
||||
-17769
File diff suppressed because it is too large
Load Diff
-8
@@ -1,8 +0,0 @@
|
||||
{ "name" : "bson"
|
||||
, "description" : "A bson parser for node.js and the browser"
|
||||
, "main": "../"
|
||||
, "directories" : { "lib" : "../lib/bson" }
|
||||
, "engines" : { "node" : ">=0.6.0" }
|
||||
, "licenses" : [ { "type" : "Apache License, Version 2.0"
|
||||
, "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ]
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
var BSON = require('./lib/bson/bson'),
|
||||
Binary = require('./lib/bson/binary'),
|
||||
Code = require('./lib/bson/code'),
|
||||
DBRef = require('./lib/bson/db_ref'),
|
||||
Decimal128 = require('./lib/bson/decimal128'),
|
||||
Double = require('./lib/bson/double'),
|
||||
Int32 = require('./lib/bson/int_32'),
|
||||
Long = require('./lib/bson/long'),
|
||||
Map = require('./lib/bson/map'),
|
||||
MaxKey = require('./lib/bson/max_key'),
|
||||
MinKey = require('./lib/bson/min_key'),
|
||||
ObjectId = require('./lib/bson/objectid'),
|
||||
BSONRegExp = require('./lib/bson/regexp'),
|
||||
Symbol = require('./lib/bson/symbol'),
|
||||
Timestamp = require('./lib/bson/timestamp');
|
||||
|
||||
// BSON MAX VALUES
|
||||
BSON.BSON_INT32_MAX = 0x7fffffff;
|
||||
BSON.BSON_INT32_MIN = -0x80000000;
|
||||
|
||||
BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;
|
||||
BSON.BSON_INT64_MIN = -Math.pow(2, 63);
|
||||
|
||||
// JS MAX PRECISE VALUES
|
||||
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
||||
// Add BSON types to function creation
|
||||
BSON.Binary = Binary;
|
||||
BSON.Code = Code;
|
||||
BSON.DBRef = DBRef;
|
||||
BSON.Decimal128 = Decimal128;
|
||||
BSON.Double = Double;
|
||||
BSON.Int32 = Int32;
|
||||
BSON.Long = Long;
|
||||
BSON.Map = Map;
|
||||
BSON.MaxKey = MaxKey;
|
||||
BSON.MinKey = MinKey;
|
||||
BSON.ObjectId = ObjectId;
|
||||
BSON.ObjectID = ObjectId;
|
||||
BSON.BSONRegExp = BSONRegExp;
|
||||
BSON.Symbol = Symbol;
|
||||
BSON.Timestamp = Timestamp;
|
||||
|
||||
// Return the BSON
|
||||
module.exports = BSON;
|
||||
-384
@@ -1,384 +0,0 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @ignore
|
||||
*/
|
||||
|
||||
// Test if we're in Node via presence of "global" not absence of "window"
|
||||
// to support hybrid environments like Electron
|
||||
if (typeof global !== 'undefined') {
|
||||
var Buffer = require('buffer').Buffer; // TODO just use global Buffer
|
||||
}
|
||||
|
||||
var utils = require('./parser/utils');
|
||||
|
||||
/**
|
||||
* A class representation of the BSON Binary type.
|
||||
*
|
||||
* Sub types
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
|
||||
*
|
||||
* @class
|
||||
* @param {Buffer} buffer a buffer object containing the binary data.
|
||||
* @param {Number} [subType] the option binary type.
|
||||
* @return {Binary}
|
||||
*/
|
||||
function Binary(buffer, subType) {
|
||||
if (!(this instanceof Binary)) return new Binary(buffer, subType);
|
||||
|
||||
if (
|
||||
buffer != null &&
|
||||
!(typeof buffer === 'string') &&
|
||||
!Buffer.isBuffer(buffer) &&
|
||||
!(buffer instanceof Uint8Array) &&
|
||||
!Array.isArray(buffer)
|
||||
) {
|
||||
throw new Error('only String, Buffer, Uint8Array or Array accepted');
|
||||
}
|
||||
|
||||
this._bsontype = 'Binary';
|
||||
|
||||
if (buffer instanceof Number) {
|
||||
this.sub_type = buffer;
|
||||
this.position = 0;
|
||||
} else {
|
||||
this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
|
||||
this.position = 0;
|
||||
}
|
||||
|
||||
if (buffer != null && !(buffer instanceof Number)) {
|
||||
// Only accept Buffer, Uint8Array or Arrays
|
||||
if (typeof buffer === 'string') {
|
||||
// Different ways of writing the length of the string for the different types
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
this.buffer = utils.toBuffer(buffer);
|
||||
} else if (
|
||||
typeof Uint8Array !== 'undefined' ||
|
||||
Object.prototype.toString.call(buffer) === '[object Array]'
|
||||
) {
|
||||
this.buffer = writeStringToArray(buffer);
|
||||
} else {
|
||||
throw new Error('only String, Buffer, Uint8Array or Array accepted');
|
||||
}
|
||||
} else {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
this.position = buffer.length;
|
||||
} else {
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE);
|
||||
} else if (typeof Uint8Array !== 'undefined') {
|
||||
this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
|
||||
} else {
|
||||
this.buffer = new Array(Binary.BUFFER_SIZE);
|
||||
}
|
||||
// Set position to start of buffer
|
||||
this.position = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this binary with byte_value.
|
||||
*
|
||||
* @method
|
||||
* @param {string} byte_value a single byte we wish to write.
|
||||
*/
|
||||
Binary.prototype.put = function put(byte_value) {
|
||||
// If it's a string and a has more than one character throw an error
|
||||
if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1)
|
||||
throw new Error('only accepts single character String, Uint8Array or Array');
|
||||
if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255)
|
||||
throw new Error('only accepts number in a valid unsigned byte range 0-255');
|
||||
|
||||
// Decode the byte value once
|
||||
var decoded_byte = null;
|
||||
if (typeof byte_value === 'string') {
|
||||
decoded_byte = byte_value.charCodeAt(0);
|
||||
} else if (byte_value['length'] != null) {
|
||||
decoded_byte = byte_value[0];
|
||||
} else {
|
||||
decoded_byte = byte_value;
|
||||
}
|
||||
|
||||
if (this.buffer.length > this.position) {
|
||||
this.buffer[this.position++] = decoded_byte;
|
||||
} else {
|
||||
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
|
||||
// Create additional overflow buffer
|
||||
var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length);
|
||||
// Combine the two buffers together
|
||||
this.buffer.copy(buffer, 0, 0, this.buffer.length);
|
||||
this.buffer = buffer;
|
||||
this.buffer[this.position++] = decoded_byte;
|
||||
} else {
|
||||
buffer = null;
|
||||
// Create a new buffer (typed or normal array)
|
||||
if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') {
|
||||
buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));
|
||||
} else {
|
||||
buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);
|
||||
}
|
||||
|
||||
// We need to copy all the content to the new array
|
||||
for (var i = 0; i < this.buffer.length; i++) {
|
||||
buffer[i] = this.buffer[i];
|
||||
}
|
||||
|
||||
// Reassign the buffer
|
||||
this.buffer = buffer;
|
||||
// Write the byte
|
||||
this.buffer[this.position++] = decoded_byte;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a buffer or string to the binary.
|
||||
*
|
||||
* @method
|
||||
* @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object.
|
||||
* @param {number} offset specify the binary of where to write the content.
|
||||
* @return {null}
|
||||
*/
|
||||
Binary.prototype.write = function write(string, offset) {
|
||||
offset = typeof offset === 'number' ? offset : this.position;
|
||||
|
||||
// If the buffer is to small let's extend the buffer
|
||||
if (this.buffer.length < offset + string.length) {
|
||||
var buffer = null;
|
||||
// If we are in node.js
|
||||
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
|
||||
buffer = utils.allocBuffer(this.buffer.length + string.length);
|
||||
this.buffer.copy(buffer, 0, 0, this.buffer.length);
|
||||
} else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') {
|
||||
// Create a new buffer
|
||||
buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length));
|
||||
// Copy the content
|
||||
for (var i = 0; i < this.position; i++) {
|
||||
buffer[i] = this.buffer[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Assign the new buffer
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {
|
||||
string.copy(this.buffer, offset, 0, string.length);
|
||||
this.position = offset + string.length > this.position ? offset + string.length : this.position;
|
||||
// offset = string.length
|
||||
} else if (
|
||||
typeof Buffer !== 'undefined' &&
|
||||
typeof string === 'string' &&
|
||||
Buffer.isBuffer(this.buffer)
|
||||
) {
|
||||
this.buffer.write(string, offset, 'binary');
|
||||
this.position = offset + string.length > this.position ? offset + string.length : this.position;
|
||||
// offset = string.length;
|
||||
} else if (
|
||||
Object.prototype.toString.call(string) === '[object Uint8Array]' ||
|
||||
(Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string')
|
||||
) {
|
||||
for (i = 0; i < string.length; i++) {
|
||||
this.buffer[offset++] = string[i];
|
||||
}
|
||||
|
||||
this.position = offset > this.position ? offset : this.position;
|
||||
} else if (typeof string === 'string') {
|
||||
for (i = 0; i < string.length; i++) {
|
||||
this.buffer[offset++] = string.charCodeAt(i);
|
||||
}
|
||||
|
||||
this.position = offset > this.position ? offset : this.position;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads **length** bytes starting at **position**.
|
||||
*
|
||||
* @method
|
||||
* @param {number} position read from the given position in the Binary.
|
||||
* @param {number} length the number of bytes to read.
|
||||
* @return {Buffer}
|
||||
*/
|
||||
Binary.prototype.read = function read(position, length) {
|
||||
length = length && length > 0 ? length : this.position;
|
||||
|
||||
// Let's return the data based on the type we have
|
||||
if (this.buffer['slice']) {
|
||||
return this.buffer.slice(position, position + length);
|
||||
} else {
|
||||
// Create a buffer to keep the result
|
||||
var buffer =
|
||||
typeof Uint8Array !== 'undefined'
|
||||
? new Uint8Array(new ArrayBuffer(length))
|
||||
: new Array(length);
|
||||
for (var i = 0; i < length; i++) {
|
||||
buffer[i] = this.buffer[position++];
|
||||
}
|
||||
}
|
||||
// Return the buffer
|
||||
return buffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the value of this binary as a string.
|
||||
*
|
||||
* @method
|
||||
* @return {string}
|
||||
*/
|
||||
Binary.prototype.value = function value(asRaw) {
|
||||
asRaw = asRaw == null ? false : asRaw;
|
||||
|
||||
// Optimize to serialize for the situation where the data == size of buffer
|
||||
if (
|
||||
asRaw &&
|
||||
typeof Buffer !== 'undefined' &&
|
||||
Buffer.isBuffer(this.buffer) &&
|
||||
this.buffer.length === this.position
|
||||
)
|
||||
return this.buffer;
|
||||
|
||||
// If it's a node.js buffer object
|
||||
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
|
||||
return asRaw
|
||||
? this.buffer.slice(0, this.position)
|
||||
: this.buffer.toString('binary', 0, this.position);
|
||||
} else {
|
||||
if (asRaw) {
|
||||
// we support the slice command use it
|
||||
if (this.buffer['slice'] != null) {
|
||||
return this.buffer.slice(0, this.position);
|
||||
} else {
|
||||
// Create a new buffer to copy content to
|
||||
var newBuffer =
|
||||
Object.prototype.toString.call(this.buffer) === '[object Uint8Array]'
|
||||
? new Uint8Array(new ArrayBuffer(this.position))
|
||||
: new Array(this.position);
|
||||
// Copy content
|
||||
for (var i = 0; i < this.position; i++) {
|
||||
newBuffer[i] = this.buffer[i];
|
||||
}
|
||||
// Return the buffer
|
||||
return newBuffer;
|
||||
}
|
||||
} else {
|
||||
return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Length.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the length of the binary.
|
||||
*/
|
||||
Binary.prototype.length = function length() {
|
||||
return this.position;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Binary.prototype.toJSON = function() {
|
||||
return this.buffer != null ? this.buffer.toString('base64') : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Binary.prototype.toString = function(format) {
|
||||
return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Binary default subtype
|
||||
* @ignore
|
||||
*/
|
||||
var BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var writeStringToArray = function(data) {
|
||||
// Create a buffer
|
||||
var buffer =
|
||||
typeof Uint8Array !== 'undefined'
|
||||
? new Uint8Array(new ArrayBuffer(data.length))
|
||||
: new Array(data.length);
|
||||
// Write the content to the buffer
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
buffer[i] = data.charCodeAt(i);
|
||||
}
|
||||
// Write the string to the buffer
|
||||
return buffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert Array ot Uint8Array to Binary String
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) {
|
||||
var result = '';
|
||||
for (var i = startIndex; i < endIndex; i++) {
|
||||
result = result + String.fromCharCode(byteArray[i]);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
Binary.BUFFER_SIZE = 256;
|
||||
|
||||
/**
|
||||
* Default BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_DEFAULT = 0;
|
||||
/**
|
||||
* Function BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_FUNCTION = 1;
|
||||
/**
|
||||
* Byte Array BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_BYTE_ARRAY = 2;
|
||||
/**
|
||||
* OLD UUID BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_UUID_OLD = 3;
|
||||
/**
|
||||
* UUID BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_UUID = 4;
|
||||
/**
|
||||
* MD5 BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_MD5 = 5;
|
||||
/**
|
||||
* User BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
module.exports = Binary;
|
||||
module.exports.Binary = Binary;
|
||||
-386
@@ -1,386 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var Map = require('./map'),
|
||||
Long = require('./long'),
|
||||
Double = require('./double'),
|
||||
Timestamp = require('./timestamp'),
|
||||
ObjectID = require('./objectid'),
|
||||
BSONRegExp = require('./regexp'),
|
||||
Symbol = require('./symbol'),
|
||||
Int32 = require('./int_32'),
|
||||
Code = require('./code'),
|
||||
Decimal128 = require('./decimal128'),
|
||||
MinKey = require('./min_key'),
|
||||
MaxKey = require('./max_key'),
|
||||
DBRef = require('./db_ref'),
|
||||
Binary = require('./binary');
|
||||
|
||||
// Parts of the parser
|
||||
var deserialize = require('./parser/deserializer'),
|
||||
serializer = require('./parser/serializer'),
|
||||
calculateObjectSize = require('./parser/calculate_size'),
|
||||
utils = require('./parser/utils');
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
// Default Max Size
|
||||
var MAXSIZE = 1024 * 1024 * 17;
|
||||
|
||||
// Current Internal Temporary Serialization Buffer
|
||||
var buffer = utils.allocBuffer(MAXSIZE);
|
||||
|
||||
var BSON = function() {};
|
||||
|
||||
/**
|
||||
* Serialize a Javascript object.
|
||||
*
|
||||
* @param {Object} object the Javascript object to serialize.
|
||||
* @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.
|
||||
* @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
|
||||
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
|
||||
* @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**.
|
||||
* @return {Buffer} returns the Buffer object containing the serialized object.
|
||||
* @api public
|
||||
*/
|
||||
BSON.prototype.serialize = function serialize(object, options) {
|
||||
options = options || {};
|
||||
// Unpack the options
|
||||
var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
|
||||
var serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
var ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
|
||||
var minInternalBufferSize =
|
||||
typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
|
||||
|
||||
// Resize the internal serialization buffer if needed
|
||||
if (buffer.length < minInternalBufferSize) {
|
||||
buffer = utils.allocBuffer(minInternalBufferSize);
|
||||
}
|
||||
|
||||
// Attempt to serialize
|
||||
var serializationIndex = serializer(
|
||||
buffer,
|
||||
object,
|
||||
checkKeys,
|
||||
0,
|
||||
0,
|
||||
serializeFunctions,
|
||||
ignoreUndefined,
|
||||
[]
|
||||
);
|
||||
// Create the final buffer
|
||||
var finishedBuffer = utils.allocBuffer(serializationIndex);
|
||||
// Copy into the finished buffer
|
||||
buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length);
|
||||
// Return the buffer
|
||||
return finishedBuffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
|
||||
*
|
||||
* @param {Object} object the Javascript object to serialize.
|
||||
* @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
|
||||
* @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.
|
||||
* @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
|
||||
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
|
||||
* @param {Number} [options.index] the index in the buffer where we wish to start serializing into.
|
||||
* @return {Number} returns the index pointing to the last written byte in the buffer.
|
||||
* @api public
|
||||
*/
|
||||
BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) {
|
||||
options = options || {};
|
||||
// Unpack the options
|
||||
var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
|
||||
var serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
var ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
|
||||
var startIndex = typeof options.index === 'number' ? options.index : 0;
|
||||
|
||||
// Attempt to serialize
|
||||
var serializationIndex = serializer(
|
||||
finalBuffer,
|
||||
object,
|
||||
checkKeys,
|
||||
startIndex || 0,
|
||||
0,
|
||||
serializeFunctions,
|
||||
ignoreUndefined
|
||||
);
|
||||
|
||||
// Return the index
|
||||
return serializationIndex - 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deserialize data as BSON.
|
||||
*
|
||||
* @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
|
||||
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
|
||||
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
|
||||
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
|
||||
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
|
||||
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.
|
||||
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
|
||||
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
|
||||
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
|
||||
* @return {Object} returns the deserialized Javascript Object.
|
||||
* @api public
|
||||
*/
|
||||
BSON.prototype.deserialize = function(buffer, options) {
|
||||
return deserialize(buffer, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculate the bson size for a passed in Javascript object.
|
||||
*
|
||||
* @param {Object} object the Javascript object to calculate the BSON byte size for.
|
||||
* @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
|
||||
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
|
||||
* @return {Number} returns the number of bytes the BSON object will take up.
|
||||
* @api public
|
||||
*/
|
||||
BSON.prototype.calculateObjectSize = function(object, options) {
|
||||
options = options || {};
|
||||
|
||||
var serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
var ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
|
||||
|
||||
return calculateObjectSize(object, serializeFunctions, ignoreUndefined);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deserialize stream data as BSON documents.
|
||||
*
|
||||
* @param {Buffer} data the buffer containing the serialized set of BSON documents.
|
||||
* @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
|
||||
* @param {Number} numberOfDocuments number of documents to deserialize.
|
||||
* @param {Array} documents an array where to store the deserialized documents.
|
||||
* @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
|
||||
* @param {Object} [options] additional options used for the deserialization.
|
||||
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
|
||||
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
|
||||
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
|
||||
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
|
||||
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.
|
||||
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
|
||||
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
|
||||
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
|
||||
* @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.
|
||||
* @api public
|
||||
*/
|
||||
BSON.prototype.deserializeStream = function(
|
||||
data,
|
||||
startIndex,
|
||||
numberOfDocuments,
|
||||
documents,
|
||||
docStartIndex,
|
||||
options
|
||||
) {
|
||||
options = options != null ? options : {};
|
||||
var index = startIndex;
|
||||
// Loop over all documents
|
||||
for (var i = 0; i < numberOfDocuments; i++) {
|
||||
// Find size of the document
|
||||
var size =
|
||||
data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24);
|
||||
// Update options with index
|
||||
options['index'] = index;
|
||||
// Parse the document at this point
|
||||
documents[docStartIndex + i] = this.deserialize(data, options);
|
||||
// Adjust index by the document size
|
||||
index = index + size;
|
||||
}
|
||||
|
||||
// Return object containing end index of parsing and list of documents
|
||||
return index;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
// BSON MAX VALUES
|
||||
BSON.BSON_INT32_MAX = 0x7fffffff;
|
||||
BSON.BSON_INT32_MIN = -0x80000000;
|
||||
|
||||
BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;
|
||||
BSON.BSON_INT64_MIN = -Math.pow(2, 63);
|
||||
|
||||
// JS MAX PRECISE VALUES
|
||||
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
||||
// Internal long versions
|
||||
// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.
|
||||
// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
||||
/**
|
||||
* Number BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_NUMBER
|
||||
**/
|
||||
BSON.BSON_DATA_NUMBER = 1;
|
||||
/**
|
||||
* String BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_STRING
|
||||
**/
|
||||
BSON.BSON_DATA_STRING = 2;
|
||||
/**
|
||||
* Object BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_OBJECT
|
||||
**/
|
||||
BSON.BSON_DATA_OBJECT = 3;
|
||||
/**
|
||||
* Array BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_ARRAY
|
||||
**/
|
||||
BSON.BSON_DATA_ARRAY = 4;
|
||||
/**
|
||||
* Binary BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_BINARY
|
||||
**/
|
||||
BSON.BSON_DATA_BINARY = 5;
|
||||
/**
|
||||
* ObjectID BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_OID
|
||||
**/
|
||||
BSON.BSON_DATA_OID = 7;
|
||||
/**
|
||||
* Boolean BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_BOOLEAN
|
||||
**/
|
||||
BSON.BSON_DATA_BOOLEAN = 8;
|
||||
/**
|
||||
* Date BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_DATE
|
||||
**/
|
||||
BSON.BSON_DATA_DATE = 9;
|
||||
/**
|
||||
* null BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_NULL
|
||||
**/
|
||||
BSON.BSON_DATA_NULL = 10;
|
||||
/**
|
||||
* RegExp BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_REGEXP
|
||||
**/
|
||||
BSON.BSON_DATA_REGEXP = 11;
|
||||
/**
|
||||
* Code BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_CODE
|
||||
**/
|
||||
BSON.BSON_DATA_CODE = 13;
|
||||
/**
|
||||
* Symbol BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_SYMBOL
|
||||
**/
|
||||
BSON.BSON_DATA_SYMBOL = 14;
|
||||
/**
|
||||
* Code with Scope BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_CODE_W_SCOPE
|
||||
**/
|
||||
BSON.BSON_DATA_CODE_W_SCOPE = 15;
|
||||
/**
|
||||
* 32 bit Integer BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_INT
|
||||
**/
|
||||
BSON.BSON_DATA_INT = 16;
|
||||
/**
|
||||
* Timestamp BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_TIMESTAMP
|
||||
**/
|
||||
BSON.BSON_DATA_TIMESTAMP = 17;
|
||||
/**
|
||||
* Long BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_LONG
|
||||
**/
|
||||
BSON.BSON_DATA_LONG = 18;
|
||||
/**
|
||||
* MinKey BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_MIN_KEY
|
||||
**/
|
||||
BSON.BSON_DATA_MIN_KEY = 0xff;
|
||||
/**
|
||||
* MaxKey BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_MAX_KEY
|
||||
**/
|
||||
BSON.BSON_DATA_MAX_KEY = 0x7f;
|
||||
|
||||
/**
|
||||
* Binary Default Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_DEFAULT
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
/**
|
||||
* Binary Function Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_FUNCTION
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
/**
|
||||
* Binary Byte Array Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
/**
|
||||
* Binary UUID Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_UUID
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
/**
|
||||
* Binary MD5 Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_MD5
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
/**
|
||||
* Binary User Defined Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
// Return BSON
|
||||
module.exports = BSON;
|
||||
module.exports.Code = Code;
|
||||
module.exports.Map = Map;
|
||||
module.exports.Symbol = Symbol;
|
||||
module.exports.BSON = BSON;
|
||||
module.exports.DBRef = DBRef;
|
||||
module.exports.Binary = Binary;
|
||||
module.exports.ObjectID = ObjectID;
|
||||
module.exports.Long = Long;
|
||||
module.exports.Timestamp = Timestamp;
|
||||
module.exports.Double = Double;
|
||||
module.exports.Int32 = Int32;
|
||||
module.exports.MinKey = MinKey;
|
||||
module.exports.MaxKey = MaxKey;
|
||||
module.exports.BSONRegExp = BSONRegExp;
|
||||
module.exports.Decimal128 = Decimal128;
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* A class representation of the BSON Code type.
|
||||
*
|
||||
* @class
|
||||
* @param {(string|function)} code a string or function.
|
||||
* @param {Object} [scope] an optional scope for the function.
|
||||
* @return {Code}
|
||||
*/
|
||||
var Code = function Code(code, scope) {
|
||||
if (!(this instanceof Code)) return new Code(code, scope);
|
||||
this._bsontype = 'Code';
|
||||
this.code = code;
|
||||
this.scope = scope;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Code.prototype.toJSON = function() {
|
||||
return { scope: this.scope, code: this.code };
|
||||
};
|
||||
|
||||
module.exports = Code;
|
||||
module.exports.Code = Code;
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* A class representation of the BSON DBRef type.
|
||||
*
|
||||
* @class
|
||||
* @param {string} namespace the collection name.
|
||||
* @param {ObjectID} oid the reference ObjectID.
|
||||
* @param {string} [db] optional db name, if omitted the reference is local to the current db.
|
||||
* @return {DBRef}
|
||||
*/
|
||||
function DBRef(namespace, oid, db) {
|
||||
if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db);
|
||||
|
||||
this._bsontype = 'DBRef';
|
||||
this.namespace = namespace;
|
||||
this.oid = oid;
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
DBRef.prototype.toJSON = function() {
|
||||
return {
|
||||
$ref: this.namespace,
|
||||
$id: this.oid,
|
||||
$db: this.db == null ? '' : this.db
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = DBRef;
|
||||
module.exports.DBRef = DBRef;
|
||||
-820
@@ -1,820 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var Long = require('./long');
|
||||
|
||||
var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
|
||||
var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
|
||||
var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
|
||||
|
||||
var EXPONENT_MAX = 6111;
|
||||
var EXPONENT_MIN = -6176;
|
||||
var EXPONENT_BIAS = 6176;
|
||||
var MAX_DIGITS = 34;
|
||||
|
||||
// Nan value bits as 32 bit values (due to lack of longs)
|
||||
var NAN_BUFFER = [
|
||||
0x7c,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00
|
||||
].reverse();
|
||||
// Infinity value bits 32 bit values (due to lack of longs)
|
||||
var INF_NEGATIVE_BUFFER = [
|
||||
0xf8,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00
|
||||
].reverse();
|
||||
var INF_POSITIVE_BUFFER = [
|
||||
0x78,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00
|
||||
].reverse();
|
||||
|
||||
var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
|
||||
|
||||
var utils = require('./parser/utils');
|
||||
|
||||
// Detect if the value is a digit
|
||||
var isDigit = function(value) {
|
||||
return !isNaN(parseInt(value, 10));
|
||||
};
|
||||
|
||||
// Divide two uint128 values
|
||||
var divideu128 = function(value) {
|
||||
var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
|
||||
var _rem = Long.fromNumber(0);
|
||||
var i = 0;
|
||||
|
||||
if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
|
||||
return { quotient: value, rem: _rem };
|
||||
}
|
||||
|
||||
for (i = 0; i <= 3; i++) {
|
||||
// Adjust remainder to match value of next dividend
|
||||
_rem = _rem.shiftLeft(32);
|
||||
// Add the divided to _rem
|
||||
_rem = _rem.add(new Long(value.parts[i], 0));
|
||||
value.parts[i] = _rem.div(DIVISOR).low_;
|
||||
_rem = _rem.modulo(DIVISOR);
|
||||
}
|
||||
|
||||
return { quotient: value, rem: _rem };
|
||||
};
|
||||
|
||||
// Multiply two Long values and return the 128 bit value
|
||||
var multiply64x2 = function(left, right) {
|
||||
if (!left && !right) {
|
||||
return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
|
||||
}
|
||||
|
||||
var leftHigh = left.shiftRightUnsigned(32);
|
||||
var leftLow = new Long(left.getLowBits(), 0);
|
||||
var rightHigh = right.shiftRightUnsigned(32);
|
||||
var rightLow = new Long(right.getLowBits(), 0);
|
||||
|
||||
var productHigh = leftHigh.multiply(rightHigh);
|
||||
var productMid = leftHigh.multiply(rightLow);
|
||||
var productMid2 = leftLow.multiply(rightHigh);
|
||||
var productLow = leftLow.multiply(rightLow);
|
||||
|
||||
productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
|
||||
productMid = new Long(productMid.getLowBits(), 0)
|
||||
.add(productMid2)
|
||||
.add(productLow.shiftRightUnsigned(32));
|
||||
|
||||
productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
|
||||
productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
|
||||
|
||||
// Return the 128 bit result
|
||||
return { high: productHigh, low: productLow };
|
||||
};
|
||||
|
||||
var lessThan = function(left, right) {
|
||||
// Make values unsigned
|
||||
var uhleft = left.high_ >>> 0;
|
||||
var uhright = right.high_ >>> 0;
|
||||
|
||||
// Compare high bits first
|
||||
if (uhleft < uhright) {
|
||||
return true;
|
||||
} else if (uhleft === uhright) {
|
||||
var ulleft = left.low_ >>> 0;
|
||||
var ulright = right.low_ >>> 0;
|
||||
if (ulleft < ulright) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
// var longtoHex = function(value) {
|
||||
// var buffer = utils.allocBuffer(8);
|
||||
// var index = 0;
|
||||
// // Encode the low 64 bits of the decimal
|
||||
// // Encode low bits
|
||||
// buffer[index++] = value.low_ & 0xff;
|
||||
// buffer[index++] = (value.low_ >> 8) & 0xff;
|
||||
// buffer[index++] = (value.low_ >> 16) & 0xff;
|
||||
// buffer[index++] = (value.low_ >> 24) & 0xff;
|
||||
// // Encode high bits
|
||||
// buffer[index++] = value.high_ & 0xff;
|
||||
// buffer[index++] = (value.high_ >> 8) & 0xff;
|
||||
// buffer[index++] = (value.high_ >> 16) & 0xff;
|
||||
// buffer[index++] = (value.high_ >> 24) & 0xff;
|
||||
// return buffer.reverse().toString('hex');
|
||||
// };
|
||||
|
||||
// var int32toHex = function(value) {
|
||||
// var buffer = utils.allocBuffer(4);
|
||||
// var index = 0;
|
||||
// // Encode the low 64 bits of the decimal
|
||||
// // Encode low bits
|
||||
// buffer[index++] = value & 0xff;
|
||||
// buffer[index++] = (value >> 8) & 0xff;
|
||||
// buffer[index++] = (value >> 16) & 0xff;
|
||||
// buffer[index++] = (value >> 24) & 0xff;
|
||||
// return buffer.reverse().toString('hex');
|
||||
// };
|
||||
|
||||
/**
|
||||
* A class representation of the BSON Decimal128 type.
|
||||
*
|
||||
* @class
|
||||
* @param {Buffer} bytes a buffer containing the raw Decimal128 bytes.
|
||||
* @return {Double}
|
||||
*/
|
||||
var Decimal128 = function(bytes) {
|
||||
this._bsontype = 'Decimal128';
|
||||
this.bytes = bytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a Decimal128 instance from a string representation
|
||||
*
|
||||
* @method
|
||||
* @param {string} string a numeric string representation.
|
||||
* @return {Decimal128} returns a Decimal128 instance.
|
||||
*/
|
||||
Decimal128.fromString = function(string) {
|
||||
// Parse state tracking
|
||||
var isNegative = false;
|
||||
var sawRadix = false;
|
||||
var foundNonZero = false;
|
||||
|
||||
// Total number of significant digits (no leading or trailing zero)
|
||||
var significantDigits = 0;
|
||||
// Total number of significand digits read
|
||||
var nDigitsRead = 0;
|
||||
// Total number of digits (no leading zeros)
|
||||
var nDigits = 0;
|
||||
// The number of the digits after radix
|
||||
var radixPosition = 0;
|
||||
// The index of the first non-zero in *str*
|
||||
var firstNonZero = 0;
|
||||
|
||||
// Digits Array
|
||||
var digits = [0];
|
||||
// The number of digits in digits
|
||||
var nDigitsStored = 0;
|
||||
// Insertion pointer for digits
|
||||
var digitsInsert = 0;
|
||||
// The index of the first non-zero digit
|
||||
var firstDigit = 0;
|
||||
// The index of the last digit
|
||||
var lastDigit = 0;
|
||||
|
||||
// Exponent
|
||||
var exponent = 0;
|
||||
// loop index over array
|
||||
var i = 0;
|
||||
// The high 17 digits of the significand
|
||||
var significandHigh = [0, 0];
|
||||
// The low 17 digits of the significand
|
||||
var significandLow = [0, 0];
|
||||
// The biased exponent
|
||||
var biasedExponent = 0;
|
||||
|
||||
// Read index
|
||||
var index = 0;
|
||||
|
||||
// Trim the string
|
||||
string = string.trim();
|
||||
|
||||
// Naively prevent against REDOS attacks.
|
||||
// TODO: implementing a custom parsing for this, or refactoring the regex would yield
|
||||
// further gains.
|
||||
if (string.length >= 7000) {
|
||||
throw new Error('' + string + ' not a valid Decimal128 string');
|
||||
}
|
||||
|
||||
// Results
|
||||
var stringMatch = string.match(PARSE_STRING_REGEXP);
|
||||
var infMatch = string.match(PARSE_INF_REGEXP);
|
||||
var nanMatch = string.match(PARSE_NAN_REGEXP);
|
||||
|
||||
// Validate the string
|
||||
if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) {
|
||||
throw new Error('' + string + ' not a valid Decimal128 string');
|
||||
}
|
||||
|
||||
// Check if we have an illegal exponent format
|
||||
if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) {
|
||||
throw new Error('' + string + ' not a valid Decimal128 string');
|
||||
}
|
||||
|
||||
// Get the negative or positive sign
|
||||
if (string[index] === '+' || string[index] === '-') {
|
||||
isNegative = string[index++] === '-';
|
||||
}
|
||||
|
||||
// Check if user passed Infinity or NaN
|
||||
if (!isDigit(string[index]) && string[index] !== '.') {
|
||||
if (string[index] === 'i' || string[index] === 'I') {
|
||||
return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
|
||||
} else if (string[index] === 'N') {
|
||||
return new Decimal128(utils.toBuffer(NAN_BUFFER));
|
||||
}
|
||||
}
|
||||
|
||||
// Read all the digits
|
||||
while (isDigit(string[index]) || string[index] === '.') {
|
||||
if (string[index] === '.') {
|
||||
if (sawRadix) {
|
||||
return new Decimal128(utils.toBuffer(NAN_BUFFER));
|
||||
}
|
||||
|
||||
sawRadix = true;
|
||||
index = index + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (nDigitsStored < 34) {
|
||||
if (string[index] !== '0' || foundNonZero) {
|
||||
if (!foundNonZero) {
|
||||
firstNonZero = nDigitsRead;
|
||||
}
|
||||
|
||||
foundNonZero = true;
|
||||
|
||||
// Only store 34 digits
|
||||
digits[digitsInsert++] = parseInt(string[index], 10);
|
||||
nDigitsStored = nDigitsStored + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundNonZero) {
|
||||
nDigits = nDigits + 1;
|
||||
}
|
||||
|
||||
if (sawRadix) {
|
||||
radixPosition = radixPosition + 1;
|
||||
}
|
||||
|
||||
nDigitsRead = nDigitsRead + 1;
|
||||
index = index + 1;
|
||||
}
|
||||
|
||||
if (sawRadix && !nDigitsRead) {
|
||||
throw new Error('' + string + ' not a valid Decimal128 string');
|
||||
}
|
||||
|
||||
// Read exponent if exists
|
||||
if (string[index] === 'e' || string[index] === 'E') {
|
||||
// Read exponent digits
|
||||
var match = string.substr(++index).match(EXPONENT_REGEX);
|
||||
|
||||
// No digits read
|
||||
if (!match || !match[2]) {
|
||||
return new Decimal128(utils.toBuffer(NAN_BUFFER));
|
||||
}
|
||||
|
||||
// Get exponent
|
||||
exponent = parseInt(match[0], 10);
|
||||
|
||||
// Adjust the index
|
||||
index = index + match[0].length;
|
||||
}
|
||||
|
||||
// Return not a number
|
||||
if (string[index]) {
|
||||
return new Decimal128(utils.toBuffer(NAN_BUFFER));
|
||||
}
|
||||
|
||||
// Done reading input
|
||||
// Find first non-zero digit in digits
|
||||
firstDigit = 0;
|
||||
|
||||
if (!nDigitsStored) {
|
||||
firstDigit = 0;
|
||||
lastDigit = 0;
|
||||
digits[0] = 0;
|
||||
nDigits = 1;
|
||||
nDigitsStored = 1;
|
||||
significantDigits = 0;
|
||||
} else {
|
||||
lastDigit = nDigitsStored - 1;
|
||||
significantDigits = nDigits;
|
||||
|
||||
if (exponent !== 0 && significantDigits !== 1) {
|
||||
while (string[firstNonZero + significantDigits - 1] === '0') {
|
||||
significantDigits = significantDigits - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Normalization of exponent
|
||||
// Correct exponent based on radix position, and shift significand as needed
|
||||
// to represent user input
|
||||
|
||||
// Overflow prevention
|
||||
if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
|
||||
exponent = EXPONENT_MIN;
|
||||
} else {
|
||||
exponent = exponent - radixPosition;
|
||||
}
|
||||
|
||||
// Attempt to normalize the exponent
|
||||
while (exponent > EXPONENT_MAX) {
|
||||
// Shift exponent to significand and decrease
|
||||
lastDigit = lastDigit + 1;
|
||||
|
||||
if (lastDigit - firstDigit > MAX_DIGITS) {
|
||||
// Check if we have a zero then just hard clamp, otherwise fail
|
||||
var digitsString = digits.join('');
|
||||
if (digitsString.match(/^0+$/)) {
|
||||
exponent = EXPONENT_MAX;
|
||||
break;
|
||||
} else {
|
||||
return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
|
||||
}
|
||||
}
|
||||
|
||||
exponent = exponent - 1;
|
||||
}
|
||||
|
||||
while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
|
||||
// Shift last digit
|
||||
if (lastDigit === 0) {
|
||||
exponent = EXPONENT_MIN;
|
||||
significantDigits = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
if (nDigitsStored < nDigits) {
|
||||
// adjust to match digits not stored
|
||||
nDigits = nDigits - 1;
|
||||
} else {
|
||||
// adjust to round
|
||||
lastDigit = lastDigit - 1;
|
||||
}
|
||||
|
||||
if (exponent < EXPONENT_MAX) {
|
||||
exponent = exponent + 1;
|
||||
} else {
|
||||
// Check if we have a zero then just hard clamp, otherwise fail
|
||||
digitsString = digits.join('');
|
||||
if (digitsString.match(/^0+$/)) {
|
||||
exponent = EXPONENT_MAX;
|
||||
break;
|
||||
} else {
|
||||
return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Round
|
||||
// We've normalized the exponent, but might still need to round.
|
||||
if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') {
|
||||
var endOfString = nDigitsRead;
|
||||
|
||||
// If we have seen a radix point, 'string' is 1 longer than we have
|
||||
// documented with ndigits_read, so inc the position of the first nonzero
|
||||
// digit and the position that digits are read to.
|
||||
if (sawRadix && exponent === EXPONENT_MIN) {
|
||||
firstNonZero = firstNonZero + 1;
|
||||
endOfString = endOfString + 1;
|
||||
}
|
||||
|
||||
var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10);
|
||||
var roundBit = 0;
|
||||
|
||||
if (roundDigit >= 5) {
|
||||
roundBit = 1;
|
||||
|
||||
if (roundDigit === 5) {
|
||||
roundBit = digits[lastDigit] % 2 === 1;
|
||||
|
||||
for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
|
||||
if (parseInt(string[i], 10)) {
|
||||
roundBit = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (roundBit) {
|
||||
var dIdx = lastDigit;
|
||||
|
||||
for (; dIdx >= 0; dIdx--) {
|
||||
if (++digits[dIdx] > 9) {
|
||||
digits[dIdx] = 0;
|
||||
|
||||
// overflowed most significant digit
|
||||
if (dIdx === 0) {
|
||||
if (exponent < EXPONENT_MAX) {
|
||||
exponent = exponent + 1;
|
||||
digits[dIdx] = 1;
|
||||
} else {
|
||||
return new Decimal128(
|
||||
utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Encode significand
|
||||
// The high 17 digits of the significand
|
||||
significandHigh = Long.fromNumber(0);
|
||||
// The low 17 digits of the significand
|
||||
significandLow = Long.fromNumber(0);
|
||||
|
||||
// read a zero
|
||||
if (significantDigits === 0) {
|
||||
significandHigh = Long.fromNumber(0);
|
||||
significandLow = Long.fromNumber(0);
|
||||
} else if (lastDigit - firstDigit < 17) {
|
||||
dIdx = firstDigit;
|
||||
significandLow = Long.fromNumber(digits[dIdx++]);
|
||||
significandHigh = new Long(0, 0);
|
||||
|
||||
for (; dIdx <= lastDigit; dIdx++) {
|
||||
significandLow = significandLow.multiply(Long.fromNumber(10));
|
||||
significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
|
||||
}
|
||||
} else {
|
||||
dIdx = firstDigit;
|
||||
significandHigh = Long.fromNumber(digits[dIdx++]);
|
||||
|
||||
for (; dIdx <= lastDigit - 17; dIdx++) {
|
||||
significandHigh = significandHigh.multiply(Long.fromNumber(10));
|
||||
significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
|
||||
}
|
||||
|
||||
significandLow = Long.fromNumber(digits[dIdx++]);
|
||||
|
||||
for (; dIdx <= lastDigit; dIdx++) {
|
||||
significandLow = significandLow.multiply(Long.fromNumber(10));
|
||||
significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
|
||||
}
|
||||
}
|
||||
|
||||
var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
|
||||
|
||||
significand.low = significand.low.add(significandLow);
|
||||
|
||||
if (lessThan(significand.low, significandLow)) {
|
||||
significand.high = significand.high.add(Long.fromNumber(1));
|
||||
}
|
||||
|
||||
// Biased exponent
|
||||
biasedExponent = exponent + EXPONENT_BIAS;
|
||||
var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
|
||||
|
||||
// Encode combination, exponent, and significand.
|
||||
if (
|
||||
significand.high
|
||||
.shiftRightUnsigned(49)
|
||||
.and(Long.fromNumber(1))
|
||||
.equals(Long.fromNumber)
|
||||
) {
|
||||
// Encode '11' into bits 1 to 3
|
||||
dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
|
||||
dec.high = dec.high.or(
|
||||
Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))
|
||||
);
|
||||
dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
|
||||
} else {
|
||||
dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
|
||||
dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
|
||||
}
|
||||
|
||||
dec.low = significand.low;
|
||||
|
||||
// Encode sign
|
||||
if (isNegative) {
|
||||
dec.high = dec.high.or(Long.fromString('9223372036854775808'));
|
||||
}
|
||||
|
||||
// Encode into a buffer
|
||||
var buffer = utils.allocBuffer(16);
|
||||
index = 0;
|
||||
|
||||
// Encode the low 64 bits of the decimal
|
||||
// Encode low bits
|
||||
buffer[index++] = dec.low.low_ & 0xff;
|
||||
buffer[index++] = (dec.low.low_ >> 8) & 0xff;
|
||||
buffer[index++] = (dec.low.low_ >> 16) & 0xff;
|
||||
buffer[index++] = (dec.low.low_ >> 24) & 0xff;
|
||||
// Encode high bits
|
||||
buffer[index++] = dec.low.high_ & 0xff;
|
||||
buffer[index++] = (dec.low.high_ >> 8) & 0xff;
|
||||
buffer[index++] = (dec.low.high_ >> 16) & 0xff;
|
||||
buffer[index++] = (dec.low.high_ >> 24) & 0xff;
|
||||
|
||||
// Encode the high 64 bits of the decimal
|
||||
// Encode low bits
|
||||
buffer[index++] = dec.high.low_ & 0xff;
|
||||
buffer[index++] = (dec.high.low_ >> 8) & 0xff;
|
||||
buffer[index++] = (dec.high.low_ >> 16) & 0xff;
|
||||
buffer[index++] = (dec.high.low_ >> 24) & 0xff;
|
||||
// Encode high bits
|
||||
buffer[index++] = dec.high.high_ & 0xff;
|
||||
buffer[index++] = (dec.high.high_ >> 8) & 0xff;
|
||||
buffer[index++] = (dec.high.high_ >> 16) & 0xff;
|
||||
buffer[index++] = (dec.high.high_ >> 24) & 0xff;
|
||||
|
||||
// Return the new Decimal128
|
||||
return new Decimal128(buffer);
|
||||
};
|
||||
|
||||
// Extract least significant 5 bits
|
||||
var COMBINATION_MASK = 0x1f;
|
||||
// Extract least significant 14 bits
|
||||
var EXPONENT_MASK = 0x3fff;
|
||||
// Value of combination field for Inf
|
||||
var COMBINATION_INFINITY = 30;
|
||||
// Value of combination field for NaN
|
||||
var COMBINATION_NAN = 31;
|
||||
// Value of combination field for NaN
|
||||
// var COMBINATION_SNAN = 32;
|
||||
// decimal128 exponent bias
|
||||
EXPONENT_BIAS = 6176;
|
||||
|
||||
/**
|
||||
* Create a string representation of the raw Decimal128 value
|
||||
*
|
||||
* @method
|
||||
* @return {string} returns a Decimal128 string representation.
|
||||
*/
|
||||
Decimal128.prototype.toString = function() {
|
||||
// Note: bits in this routine are referred to starting at 0,
|
||||
// from the sign bit, towards the coefficient.
|
||||
|
||||
// bits 0 - 31
|
||||
var high;
|
||||
// bits 32 - 63
|
||||
var midh;
|
||||
// bits 64 - 95
|
||||
var midl;
|
||||
// bits 96 - 127
|
||||
var low;
|
||||
// bits 1 - 5
|
||||
var combination;
|
||||
// decoded biased exponent (14 bits)
|
||||
var biased_exponent;
|
||||
// the number of significand digits
|
||||
var significand_digits = 0;
|
||||
// the base-10 digits in the significand
|
||||
var significand = new Array(36);
|
||||
for (var i = 0; i < significand.length; i++) significand[i] = 0;
|
||||
// read pointer into significand
|
||||
var index = 0;
|
||||
|
||||
// unbiased exponent
|
||||
var exponent;
|
||||
// the exponent if scientific notation is used
|
||||
var scientific_exponent;
|
||||
|
||||
// true if the number is zero
|
||||
var is_zero = false;
|
||||
|
||||
// the most signifcant significand bits (50-46)
|
||||
var significand_msb;
|
||||
// temporary storage for significand decoding
|
||||
var significand128 = { parts: new Array(4) };
|
||||
// indexing variables
|
||||
i;
|
||||
var j, k;
|
||||
|
||||
// Output string
|
||||
var string = [];
|
||||
|
||||
// Unpack index
|
||||
index = 0;
|
||||
|
||||
// Buffer reference
|
||||
var buffer = this.bytes;
|
||||
|
||||
// Unpack the low 64bits into a long
|
||||
low =
|
||||
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
|
||||
midl =
|
||||
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
|
||||
|
||||
// Unpack the high 64bits into a long
|
||||
midh =
|
||||
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
|
||||
high =
|
||||
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
|
||||
|
||||
// Unpack index
|
||||
index = 0;
|
||||
|
||||
// Create the state of the decimal
|
||||
var dec = {
|
||||
low: new Long(low, midl),
|
||||
high: new Long(midh, high)
|
||||
};
|
||||
|
||||
if (dec.high.lessThan(Long.ZERO)) {
|
||||
string.push('-');
|
||||
}
|
||||
|
||||
// Decode combination field and exponent
|
||||
combination = (high >> 26) & COMBINATION_MASK;
|
||||
|
||||
if (combination >> 3 === 3) {
|
||||
// Check for 'special' values
|
||||
if (combination === COMBINATION_INFINITY) {
|
||||
return string.join('') + 'Infinity';
|
||||
} else if (combination === COMBINATION_NAN) {
|
||||
return 'NaN';
|
||||
} else {
|
||||
biased_exponent = (high >> 15) & EXPONENT_MASK;
|
||||
significand_msb = 0x08 + ((high >> 14) & 0x01);
|
||||
}
|
||||
} else {
|
||||
significand_msb = (high >> 14) & 0x07;
|
||||
biased_exponent = (high >> 17) & EXPONENT_MASK;
|
||||
}
|
||||
|
||||
exponent = biased_exponent - EXPONENT_BIAS;
|
||||
|
||||
// Create string of significand digits
|
||||
|
||||
// Convert the 114-bit binary number represented by
|
||||
// (significand_high, significand_low) to at most 34 decimal
|
||||
// digits through modulo and division.
|
||||
significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
|
||||
significand128.parts[1] = midh;
|
||||
significand128.parts[2] = midl;
|
||||
significand128.parts[3] = low;
|
||||
|
||||
if (
|
||||
significand128.parts[0] === 0 &&
|
||||
significand128.parts[1] === 0 &&
|
||||
significand128.parts[2] === 0 &&
|
||||
significand128.parts[3] === 0
|
||||
) {
|
||||
is_zero = true;
|
||||
} else {
|
||||
for (k = 3; k >= 0; k--) {
|
||||
var least_digits = 0;
|
||||
// Peform the divide
|
||||
var result = divideu128(significand128);
|
||||
significand128 = result.quotient;
|
||||
least_digits = result.rem.low_;
|
||||
|
||||
// We now have the 9 least significant digits (in base 2).
|
||||
// Convert and output to string.
|
||||
if (!least_digits) continue;
|
||||
|
||||
for (j = 8; j >= 0; j--) {
|
||||
// significand[k * 9 + j] = Math.round(least_digits % 10);
|
||||
significand[k * 9 + j] = least_digits % 10;
|
||||
// least_digits = Math.round(least_digits / 10);
|
||||
least_digits = Math.floor(least_digits / 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Output format options:
|
||||
// Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
|
||||
// Regular - ddd.ddd
|
||||
|
||||
if (is_zero) {
|
||||
significand_digits = 1;
|
||||
significand[index] = 0;
|
||||
} else {
|
||||
significand_digits = 36;
|
||||
i = 0;
|
||||
|
||||
while (!significand[index]) {
|
||||
i++;
|
||||
significand_digits = significand_digits - 1;
|
||||
index = index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
scientific_exponent = significand_digits - 1 + exponent;
|
||||
|
||||
// The scientific exponent checks are dictated by the string conversion
|
||||
// specification and are somewhat arbitrary cutoffs.
|
||||
//
|
||||
// We must check exponent > 0, because if this is the case, the number
|
||||
// has trailing zeros. However, we *cannot* output these trailing zeros,
|
||||
// because doing so would change the precision of the value, and would
|
||||
// change stored data if the string converted number is round tripped.
|
||||
|
||||
if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
|
||||
// Scientific format
|
||||
string.push(significand[index++]);
|
||||
significand_digits = significand_digits - 1;
|
||||
|
||||
if (significand_digits) {
|
||||
string.push('.');
|
||||
}
|
||||
|
||||
for (i = 0; i < significand_digits; i++) {
|
||||
string.push(significand[index++]);
|
||||
}
|
||||
|
||||
// Exponent
|
||||
string.push('E');
|
||||
if (scientific_exponent > 0) {
|
||||
string.push('+' + scientific_exponent);
|
||||
} else {
|
||||
string.push(scientific_exponent);
|
||||
}
|
||||
} else {
|
||||
// Regular format with no decimal place
|
||||
if (exponent >= 0) {
|
||||
for (i = 0; i < significand_digits; i++) {
|
||||
string.push(significand[index++]);
|
||||
}
|
||||
} else {
|
||||
var radix_position = significand_digits + exponent;
|
||||
|
||||
// non-zero digits before radix
|
||||
if (radix_position > 0) {
|
||||
for (i = 0; i < radix_position; i++) {
|
||||
string.push(significand[index++]);
|
||||
}
|
||||
} else {
|
||||
string.push('0');
|
||||
}
|
||||
|
||||
string.push('.');
|
||||
// add leading zeros after radix
|
||||
while (radix_position++ < 0) {
|
||||
string.push('0');
|
||||
}
|
||||
|
||||
for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
|
||||
string.push(significand[index++]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return string.join('');
|
||||
};
|
||||
|
||||
Decimal128.prototype.toJSON = function() {
|
||||
return { $numberDecimal: this.toString() };
|
||||
};
|
||||
|
||||
module.exports = Decimal128;
|
||||
module.exports.Decimal128 = Decimal128;
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* A class representation of the BSON Double type.
|
||||
*
|
||||
* @class
|
||||
* @param {number} value the number we want to represent as a double.
|
||||
* @return {Double}
|
||||
*/
|
||||
function Double(value) {
|
||||
if (!(this instanceof Double)) return new Double(value);
|
||||
|
||||
this._bsontype = 'Double';
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access the number value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} returns the wrapped double number.
|
||||
*/
|
||||
Double.prototype.valueOf = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Double.prototype.toJSON = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
module.exports = Double;
|
||||
module.exports.Double = Double;
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
// Copyright (c) 2008, Fair Oaks Labs, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
|
||||
// may be used to endorse or promote products derived from this software
|
||||
// without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
// POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
//
|
||||
// Modifications to writeIEEE754 to support negative zeroes made by Brian White
|
||||
|
||||
var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) {
|
||||
var e,
|
||||
m,
|
||||
bBE = endian === 'big',
|
||||
eLen = nBytes * 8 - mLen - 1,
|
||||
eMax = (1 << eLen) - 1,
|
||||
eBias = eMax >> 1,
|
||||
nBits = -7,
|
||||
i = bBE ? 0 : nBytes - 1,
|
||||
d = bBE ? 1 : -1,
|
||||
s = buffer[offset + i];
|
||||
|
||||
i += d;
|
||||
|
||||
e = s & ((1 << -nBits) - 1);
|
||||
s >>= -nBits;
|
||||
nBits += eLen;
|
||||
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
|
||||
|
||||
m = e & ((1 << -nBits) - 1);
|
||||
e >>= -nBits;
|
||||
nBits += mLen;
|
||||
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
|
||||
|
||||
if (e === 0) {
|
||||
e = 1 - eBias;
|
||||
} else if (e === eMax) {
|
||||
return m ? NaN : (s ? -1 : 1) * Infinity;
|
||||
} else {
|
||||
m = m + Math.pow(2, mLen);
|
||||
e = e - eBias;
|
||||
}
|
||||
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
|
||||
};
|
||||
|
||||
var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) {
|
||||
var e,
|
||||
m,
|
||||
c,
|
||||
bBE = endian === 'big',
|
||||
eLen = nBytes * 8 - mLen - 1,
|
||||
eMax = (1 << eLen) - 1,
|
||||
eBias = eMax >> 1,
|
||||
rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0,
|
||||
i = bBE ? nBytes - 1 : 0,
|
||||
d = bBE ? -1 : 1,
|
||||
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
|
||||
|
||||
value = Math.abs(value);
|
||||
|
||||
if (isNaN(value) || value === Infinity) {
|
||||
m = isNaN(value) ? 1 : 0;
|
||||
e = eMax;
|
||||
} else {
|
||||
e = Math.floor(Math.log(value) / Math.LN2);
|
||||
if (value * (c = Math.pow(2, -e)) < 1) {
|
||||
e--;
|
||||
c *= 2;
|
||||
}
|
||||
if (e + eBias >= 1) {
|
||||
value += rt / c;
|
||||
} else {
|
||||
value += rt * Math.pow(2, 1 - eBias);
|
||||
}
|
||||
if (value * c >= 2) {
|
||||
e++;
|
||||
c /= 2;
|
||||
}
|
||||
|
||||
if (e + eBias >= eMax) {
|
||||
m = 0;
|
||||
e = eMax;
|
||||
} else if (e + eBias >= 1) {
|
||||
m = (value * c - 1) * Math.pow(2, mLen);
|
||||
e = e + eBias;
|
||||
} else {
|
||||
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
|
||||
e = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
|
||||
|
||||
e = (e << mLen) | m;
|
||||
eLen += mLen;
|
||||
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
|
||||
|
||||
buffer[offset + i - d] |= s * 128;
|
||||
};
|
||||
|
||||
exports.readIEEE754 = readIEEE754;
|
||||
exports.writeIEEE754 = writeIEEE754;
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* A class representation of a BSON Int32 type.
|
||||
*
|
||||
* @class
|
||||
* @param {number} value the number we want to represent as an int32.
|
||||
* @return {Int32}
|
||||
*/
|
||||
var Int32 = function(value) {
|
||||
if (!(this instanceof Int32)) return new Int32(value);
|
||||
|
||||
this._bsontype = 'Int32';
|
||||
this.value = value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Access the number value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} returns the wrapped int32 number.
|
||||
*/
|
||||
Int32.prototype.valueOf = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Int32.prototype.toJSON = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
module.exports = Int32;
|
||||
module.exports.Int32 = Int32;
|
||||
-851
@@ -1,851 +0,0 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright 2009 Google Inc. All Rights Reserved
|
||||
|
||||
/**
|
||||
* Defines a Long class for representing a 64-bit two's-complement
|
||||
* integer value, which faithfully simulates the behavior of a Java "Long". This
|
||||
* implementation is derived from LongLib in GWT.
|
||||
*
|
||||
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
|
||||
* values as *signed* integers. See the from* functions below for more
|
||||
* convenient ways of constructing Longs.
|
||||
*
|
||||
* The internal representation of a Long is the two given signed, 32-bit values.
|
||||
* We use 32-bit pieces because these are the size of integers on which
|
||||
* Javascript performs bit-operations. For operations like addition and
|
||||
* multiplication, we split each number into 16-bit pieces, which can easily be
|
||||
* multiplied within Javascript's floating-point representation without overflow
|
||||
* or change in sign.
|
||||
*
|
||||
* In the algorithms below, we frequently reduce the negative case to the
|
||||
* positive case by negating the input(s) and then post-processing the result.
|
||||
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
|
||||
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
|
||||
* a positive number, it overflows back into a negative). Not handling this
|
||||
* case would often result in infinite recursion.
|
||||
*
|
||||
* @class
|
||||
* @param {number} low the low (signed) 32 bits of the Long.
|
||||
* @param {number} high the high (signed) 32 bits of the Long.
|
||||
* @return {Long}
|
||||
*/
|
||||
function Long(low, high) {
|
||||
if (!(this instanceof Long)) return new Long(low, high);
|
||||
|
||||
this._bsontype = 'Long';
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
this.high_ = high | 0; // force into 32 signed bits.
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the int value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the value, assuming it is a 32-bit integer.
|
||||
*/
|
||||
Long.prototype.toInt = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the Number value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the closest floating-point representation to this value.
|
||||
*/
|
||||
Long.prototype.toNumber = function() {
|
||||
return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the JSON value.
|
||||
*
|
||||
* @method
|
||||
* @return {string} the JSON representation.
|
||||
*/
|
||||
Long.prototype.toJSON = function() {
|
||||
return this.toString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the String value.
|
||||
*
|
||||
* @method
|
||||
* @param {number} [opt_radix] the radix in which the text should be written.
|
||||
* @return {string} the textual representation of this value.
|
||||
*/
|
||||
Long.prototype.toString = function(opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (this.isZero()) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
// We need to change the Long value before it can be negated, so we remove
|
||||
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
var radixLong = Long.fromNumber(radix);
|
||||
var div = this.div(radixLong);
|
||||
var rem = div.multiply(radixLong).subtract(this);
|
||||
return div.toString(radix) + rem.toInt().toString(radix);
|
||||
} else {
|
||||
return '-' + this.negate().toString(radix);
|
||||
}
|
||||
}
|
||||
|
||||
// Do several (6) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Long.fromNumber(Math.pow(radix, 6));
|
||||
|
||||
rem = this;
|
||||
var result = '';
|
||||
|
||||
while (!rem.isZero()) {
|
||||
var remDiv = rem.div(radixToPower);
|
||||
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
|
||||
var digits = intval.toString(radix);
|
||||
|
||||
rem = remDiv;
|
||||
if (rem.isZero()) {
|
||||
return digits + result;
|
||||
} else {
|
||||
while (digits.length < 6) {
|
||||
digits = '0' + digits;
|
||||
}
|
||||
result = '' + digits + result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the high 32-bits value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the high 32-bits as a signed value.
|
||||
*/
|
||||
Long.prototype.getHighBits = function() {
|
||||
return this.high_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low 32-bits value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the low 32-bits as a signed value.
|
||||
*/
|
||||
Long.prototype.getLowBits = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low unsigned 32-bits value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the low 32-bits as an unsigned value.
|
||||
*/
|
||||
Long.prototype.getLowBitsUnsigned = function() {
|
||||
return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the number of bits needed to represent the absolute value of this Long.
|
||||
*
|
||||
* @method
|
||||
* @return {number} Returns the number of bits needed to represent the absolute value of this Long.
|
||||
*/
|
||||
Long.prototype.getNumBitsAbs = function() {
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
return 64;
|
||||
} else {
|
||||
return this.negate().getNumBitsAbs();
|
||||
}
|
||||
} else {
|
||||
var val = this.high_ !== 0 ? this.high_ : this.low_;
|
||||
for (var bit = 31; bit > 0; bit--) {
|
||||
if ((val & (1 << bit)) !== 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return this.high_ !== 0 ? bit + 33 : bit + 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is zero.
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} whether this value is zero.
|
||||
*/
|
||||
Long.prototype.isZero = function() {
|
||||
return this.high_ === 0 && this.low_ === 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is negative.
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} whether this value is negative.
|
||||
*/
|
||||
Long.prototype.isNegative = function() {
|
||||
return this.high_ < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is odd.
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} whether this value is odd.
|
||||
*/
|
||||
Long.prototype.isOdd = function() {
|
||||
return (this.low_ & 1) === 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long equals the other
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} whether this Long equals the other
|
||||
*/
|
||||
Long.prototype.equals = function(other) {
|
||||
return this.high_ === other.high_ && this.low_ === other.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long does not equal the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} whether this Long does not equal the other.
|
||||
*/
|
||||
Long.prototype.notEquals = function(other) {
|
||||
return this.high_ !== other.high_ || this.low_ !== other.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is less than the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} whether this Long is less than the other.
|
||||
*/
|
||||
Long.prototype.lessThan = function(other) {
|
||||
return this.compare(other) < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is less than or equal to the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} whether this Long is less than or equal to the other.
|
||||
*/
|
||||
Long.prototype.lessThanOrEqual = function(other) {
|
||||
return this.compare(other) <= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is greater than the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} whether this Long is greater than the other.
|
||||
*/
|
||||
Long.prototype.greaterThan = function(other) {
|
||||
return this.compare(other) > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is greater than or equal to the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} whether this Long is greater than or equal to the other.
|
||||
*/
|
||||
Long.prototype.greaterThanOrEqual = function(other) {
|
||||
return this.compare(other) >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares this Long with the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
|
||||
*/
|
||||
Long.prototype.compare = function(other) {
|
||||
if (this.equals(other)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var thisNeg = this.isNegative();
|
||||
var otherNeg = other.isNegative();
|
||||
if (thisNeg && !otherNeg) {
|
||||
return -1;
|
||||
}
|
||||
if (!thisNeg && otherNeg) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// at this point, the signs are the same, so subtraction will not overflow
|
||||
if (this.subtract(other).isNegative()) {
|
||||
return -1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The negation of this value.
|
||||
*
|
||||
* @method
|
||||
* @return {Long} the negation of this value.
|
||||
*/
|
||||
Long.prototype.negate = function() {
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
return Long.MIN_VALUE;
|
||||
} else {
|
||||
return this.not().add(Long.ONE);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the sum of this and the given Long.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to add to this one.
|
||||
* @return {Long} the sum of this and the given Long.
|
||||
*/
|
||||
Long.prototype.add = function(other) {
|
||||
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xffff;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xffff;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xffff;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xffff;
|
||||
|
||||
var c48 = 0,
|
||||
c32 = 0,
|
||||
c16 = 0,
|
||||
c00 = 0;
|
||||
c00 += a00 + b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xffff;
|
||||
c16 += a16 + b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xffff;
|
||||
c32 += a32 + b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c48 += a48 + b48;
|
||||
c48 &= 0xffff;
|
||||
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the difference of this and the given Long.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to subtract from this.
|
||||
* @return {Long} the difference of this and the given Long.
|
||||
*/
|
||||
Long.prototype.subtract = function(other) {
|
||||
return this.add(other.negate());
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the product of this and the given Long.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long to multiply with this.
|
||||
* @return {Long} the product of this and the other.
|
||||
*/
|
||||
Long.prototype.multiply = function(other) {
|
||||
if (this.isZero()) {
|
||||
return Long.ZERO;
|
||||
} else if (other.isZero()) {
|
||||
return Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
return other.isOdd() ? Long.MIN_VALUE : Long.ZERO;
|
||||
} else if (other.equals(Long.MIN_VALUE)) {
|
||||
return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().multiply(other.negate());
|
||||
} else {
|
||||
return this.negate()
|
||||
.multiply(other)
|
||||
.negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.multiply(other.negate()).negate();
|
||||
}
|
||||
|
||||
// If both Longs are small, use float multiplication
|
||||
if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) {
|
||||
return Long.fromNumber(this.toNumber() * other.toNumber());
|
||||
}
|
||||
|
||||
// Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
// We can skip products that would overflow.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xffff;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xffff;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xffff;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xffff;
|
||||
|
||||
var c48 = 0,
|
||||
c32 = 0,
|
||||
c16 = 0,
|
||||
c00 = 0;
|
||||
c00 += a00 * b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xffff;
|
||||
c16 += a16 * b00;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xffff;
|
||||
c16 += a00 * b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xffff;
|
||||
c32 += a32 * b00;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c32 += a16 * b16;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c32 += a00 * b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
|
||||
c48 &= 0xffff;
|
||||
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long divided by the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long by which to divide.
|
||||
* @return {Long} this Long divided by the given one.
|
||||
*/
|
||||
Long.prototype.div = function(other) {
|
||||
if (other.isZero()) {
|
||||
throw Error('division by zero');
|
||||
} else if (this.isZero()) {
|
||||
return Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) {
|
||||
return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
||||
} else if (other.equals(Long.MIN_VALUE)) {
|
||||
return Long.ONE;
|
||||
} else {
|
||||
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
var halfThis = this.shiftRight(1);
|
||||
var approx = halfThis.div(other).shiftLeft(1);
|
||||
if (approx.equals(Long.ZERO)) {
|
||||
return other.isNegative() ? Long.ONE : Long.NEG_ONE;
|
||||
} else {
|
||||
var rem = this.subtract(other.multiply(approx));
|
||||
var result = approx.add(rem.div(other));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (other.equals(Long.MIN_VALUE)) {
|
||||
return Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().div(other.negate());
|
||||
} else {
|
||||
return this.negate()
|
||||
.div(other)
|
||||
.negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.div(other.negate()).negate();
|
||||
}
|
||||
|
||||
// Repeat the following until the remainder is less than other: find a
|
||||
// floating-point that approximates remainder / other *from below*, add this
|
||||
// into the result, and subtract it from the remainder. It is critical that
|
||||
// the approximate value is less than or equal to the real value so that the
|
||||
// remainder never becomes negative.
|
||||
var res = Long.ZERO;
|
||||
rem = this;
|
||||
while (rem.greaterThanOrEqual(other)) {
|
||||
// Approximate the result of division. This may be a little greater or
|
||||
// smaller than the actual value.
|
||||
approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
|
||||
|
||||
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
// the smallest non-fractional digit, whichever is larger.
|
||||
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
|
||||
var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
|
||||
|
||||
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
// that if it is too large, the product overflows and is negative.
|
||||
var approxRes = Long.fromNumber(approx);
|
||||
var approxRem = approxRes.multiply(other);
|
||||
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
|
||||
approx -= delta;
|
||||
approxRes = Long.fromNumber(approx);
|
||||
approxRem = approxRes.multiply(other);
|
||||
}
|
||||
|
||||
// We know the answer can't be zero... and actually, zero would cause
|
||||
// infinite recursion since we would make no progress.
|
||||
if (approxRes.isZero()) {
|
||||
approxRes = Long.ONE;
|
||||
}
|
||||
|
||||
res = res.add(approxRes);
|
||||
rem = rem.subtract(approxRem);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long modulo the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other Long by which to mod.
|
||||
* @return {Long} this Long modulo the given one.
|
||||
*/
|
||||
Long.prototype.modulo = function(other) {
|
||||
return this.subtract(this.div(other).multiply(other));
|
||||
};
|
||||
|
||||
/**
|
||||
* The bitwise-NOT of this value.
|
||||
*
|
||||
* @method
|
||||
* @return {Long} the bitwise-NOT of this value.
|
||||
*/
|
||||
Long.prototype.not = function() {
|
||||
return Long.fromBits(~this.low_, ~this.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-AND of this Long and the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other the Long with which to AND.
|
||||
* @return {Long} the bitwise-AND of this and the other.
|
||||
*/
|
||||
Long.prototype.and = function(other) {
|
||||
return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-OR of this Long and the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other the Long with which to OR.
|
||||
* @return {Long} the bitwise-OR of this and the other.
|
||||
*/
|
||||
Long.prototype.or = function(other) {
|
||||
return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-XOR of this Long and the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Long} other the Long with which to XOR.
|
||||
* @return {Long} the bitwise-XOR of this and the other.
|
||||
*/
|
||||
Long.prototype.xor = function(other) {
|
||||
return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the left by the given amount.
|
||||
*
|
||||
* @method
|
||||
* @param {number} numBits the number of bits by which to shift.
|
||||
* @return {Long} this shifted to the left by the given amount.
|
||||
*/
|
||||
Long.prototype.shiftLeft = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits === 0) {
|
||||
return this;
|
||||
} else {
|
||||
var low = this.low_;
|
||||
if (numBits < 32) {
|
||||
var high = this.high_;
|
||||
return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits)));
|
||||
} else {
|
||||
return Long.fromBits(0, low << (numBits - 32));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the right by the given amount.
|
||||
*
|
||||
* @method
|
||||
* @param {number} numBits the number of bits by which to shift.
|
||||
* @return {Long} this shifted to the right by the given amount.
|
||||
*/
|
||||
Long.prototype.shiftRight = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits === 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits);
|
||||
} else {
|
||||
return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
|
||||
*
|
||||
* @method
|
||||
* @param {number} numBits the number of bits by which to shift.
|
||||
* @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits.
|
||||
*/
|
||||
Long.prototype.shiftRightUnsigned = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits === 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits);
|
||||
} else if (numBits === 32) {
|
||||
return Long.fromBits(high, 0);
|
||||
} else {
|
||||
return Long.fromBits(high >>> (numBits - 32), 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representing the given (32-bit) integer value.
|
||||
*
|
||||
* @method
|
||||
* @param {number} value the 32-bit integer in question.
|
||||
* @return {Long} the corresponding Long value.
|
||||
*/
|
||||
Long.fromInt = function(value) {
|
||||
if (-128 <= value && value < 128) {
|
||||
var cachedObj = Long.INT_CACHE_[value];
|
||||
if (cachedObj) {
|
||||
return cachedObj;
|
||||
}
|
||||
}
|
||||
|
||||
var obj = new Long(value | 0, value < 0 ? -1 : 0);
|
||||
if (-128 <= value && value < 128) {
|
||||
Long.INT_CACHE_[value] = obj;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
|
||||
*
|
||||
* @method
|
||||
* @param {number} value the number in question.
|
||||
* @return {Long} the corresponding Long value.
|
||||
*/
|
||||
Long.fromNumber = function(value) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return Long.ZERO;
|
||||
} else if (value <= -Long.TWO_PWR_63_DBL_) {
|
||||
return Long.MIN_VALUE;
|
||||
} else if (value + 1 >= Long.TWO_PWR_63_DBL_) {
|
||||
return Long.MAX_VALUE;
|
||||
} else if (value < 0) {
|
||||
return Long.fromNumber(-value).negate();
|
||||
} else {
|
||||
return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
|
||||
*
|
||||
* @method
|
||||
* @param {number} lowBits the low 32-bits.
|
||||
* @param {number} highBits the high 32-bits.
|
||||
* @return {Long} the corresponding Long value.
|
||||
*/
|
||||
Long.fromBits = function(lowBits, highBits) {
|
||||
return new Long(lowBits, highBits);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representation of the given string, written using the given radix.
|
||||
*
|
||||
* @method
|
||||
* @param {string} str the textual representation of the Long.
|
||||
* @param {number} opt_radix the radix in which the text is written.
|
||||
* @return {Long} the corresponding Long value.
|
||||
*/
|
||||
Long.fromString = function(str, opt_radix) {
|
||||
if (str.length === 0) {
|
||||
throw Error('number format error: empty string');
|
||||
}
|
||||
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (str.charAt(0) === '-') {
|
||||
return Long.fromString(str.substring(1), radix).negate();
|
||||
} else if (str.indexOf('-') >= 0) {
|
||||
throw Error('number format error: interior "-" character: ' + str);
|
||||
}
|
||||
|
||||
// Do several (8) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Long.fromNumber(Math.pow(radix, 8));
|
||||
|
||||
var result = Long.ZERO;
|
||||
for (var i = 0; i < str.length; i += 8) {
|
||||
var size = Math.min(8, str.length - i);
|
||||
var value = parseInt(str.substring(i, i + size), radix);
|
||||
if (size < 8) {
|
||||
var power = Long.fromNumber(Math.pow(radix, size));
|
||||
result = result.multiply(power).add(Long.fromNumber(value));
|
||||
} else {
|
||||
result = result.multiply(radixToPower);
|
||||
result = result.add(Long.fromNumber(value));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
// from* methods on which they depend.
|
||||
|
||||
/**
|
||||
* A cache of the Long representations of small integer values.
|
||||
* @type {Object}
|
||||
* @ignore
|
||||
*/
|
||||
Long.INT_CACHE_ = {};
|
||||
|
||||
// NOTE: the compiler should inline these constant values below and then remove
|
||||
// these variables, so there should be no runtime penalty for these.
|
||||
|
||||
/**
|
||||
* Number used repeated below in calculations. This must appear before the
|
||||
* first call to any from* function below.
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_16_DBL_ = 1 << 16;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_24_DBL_ = 1 << 24;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2;
|
||||
|
||||
/** @type {Long} */
|
||||
Long.ZERO = Long.fromInt(0);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.ONE = Long.fromInt(1);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.NEG_ONE = Long.fromInt(-1);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0);
|
||||
|
||||
/**
|
||||
* @type {Long}
|
||||
* @ignore
|
||||
*/
|
||||
Long.TWO_PWR_24_ = Long.fromInt(1 << 24);
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
module.exports = Long;
|
||||
module.exports.Long = Long;
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// We have an ES6 Map available, return the native instance
|
||||
if (typeof global.Map !== 'undefined') {
|
||||
module.exports = global.Map;
|
||||
module.exports.Map = global.Map;
|
||||
} else {
|
||||
// We will return a polyfill
|
||||
var Map = function(array) {
|
||||
this._keys = [];
|
||||
this._values = {};
|
||||
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
if (array[i] == null) continue; // skip null and undefined
|
||||
var entry = array[i];
|
||||
var key = entry[0];
|
||||
var value = entry[1];
|
||||
// Add the key to the list of keys in order
|
||||
this._keys.push(key);
|
||||
// Add the key and value to the values dictionary with a point
|
||||
// to the location in the ordered keys list
|
||||
this._values[key] = { v: value, i: this._keys.length - 1 };
|
||||
}
|
||||
};
|
||||
|
||||
Map.prototype.clear = function() {
|
||||
this._keys = [];
|
||||
this._values = {};
|
||||
};
|
||||
|
||||
Map.prototype.delete = function(key) {
|
||||
var value = this._values[key];
|
||||
if (value == null) return false;
|
||||
// Delete entry
|
||||
delete this._values[key];
|
||||
// Remove the key from the ordered keys list
|
||||
this._keys.splice(value.i, 1);
|
||||
return true;
|
||||
};
|
||||
|
||||
Map.prototype.entries = function() {
|
||||
var self = this;
|
||||
var index = 0;
|
||||
|
||||
return {
|
||||
next: function() {
|
||||
var key = self._keys[index++];
|
||||
return {
|
||||
value: key !== undefined ? [key, self._values[key].v] : undefined,
|
||||
done: key !== undefined ? false : true
|
||||
};
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Map.prototype.forEach = function(callback, self) {
|
||||
self = self || this;
|
||||
|
||||
for (var i = 0; i < this._keys.length; i++) {
|
||||
var key = this._keys[i];
|
||||
// Call the forEach callback
|
||||
callback.call(self, this._values[key].v, key, self);
|
||||
}
|
||||
};
|
||||
|
||||
Map.prototype.get = function(key) {
|
||||
return this._values[key] ? this._values[key].v : undefined;
|
||||
};
|
||||
|
||||
Map.prototype.has = function(key) {
|
||||
return this._values[key] != null;
|
||||
};
|
||||
|
||||
Map.prototype.keys = function() {
|
||||
var self = this;
|
||||
var index = 0;
|
||||
|
||||
return {
|
||||
next: function() {
|
||||
var key = self._keys[index++];
|
||||
return {
|
||||
value: key !== undefined ? key : undefined,
|
||||
done: key !== undefined ? false : true
|
||||
};
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Map.prototype.set = function(key, value) {
|
||||
if (this._values[key]) {
|
||||
this._values[key].v = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
// Add the key to the list of keys in order
|
||||
this._keys.push(key);
|
||||
// Add the key and value to the values dictionary with a point
|
||||
// to the location in the ordered keys list
|
||||
this._values[key] = { v: value, i: this._keys.length - 1 };
|
||||
return this;
|
||||
};
|
||||
|
||||
Map.prototype.values = function() {
|
||||
var self = this;
|
||||
var index = 0;
|
||||
|
||||
return {
|
||||
next: function() {
|
||||
var key = self._keys[index++];
|
||||
return {
|
||||
value: key !== undefined ? self._values[key].v : undefined,
|
||||
done: key !== undefined ? false : true
|
||||
};
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Last ismaster
|
||||
Object.defineProperty(Map.prototype, 'size', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this._keys.length;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = Map;
|
||||
module.exports.Map = Map;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* A class representation of the BSON MaxKey type.
|
||||
*
|
||||
* @class
|
||||
* @return {MaxKey} A MaxKey instance
|
||||
*/
|
||||
function MaxKey() {
|
||||
if (!(this instanceof MaxKey)) return new MaxKey();
|
||||
|
||||
this._bsontype = 'MaxKey';
|
||||
}
|
||||
|
||||
module.exports = MaxKey;
|
||||
module.exports.MaxKey = MaxKey;
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* A class representation of the BSON MinKey type.
|
||||
*
|
||||
* @class
|
||||
* @return {MinKey} A MinKey instance
|
||||
*/
|
||||
function MinKey() {
|
||||
if (!(this instanceof MinKey)) return new MinKey();
|
||||
|
||||
this._bsontype = 'MinKey';
|
||||
}
|
||||
|
||||
module.exports = MinKey;
|
||||
module.exports.MinKey = MinKey;
|
||||
-389
@@ -1,389 +0,0 @@
|
||||
// Custom inspect property name / symbol.
|
||||
var inspect = 'inspect';
|
||||
|
||||
var utils = require('./parser/utils');
|
||||
|
||||
/**
|
||||
* Machine id.
|
||||
*
|
||||
* Create a random 3-byte value (i.e. unique for this
|
||||
* process). Other drivers use a md5 of the machine id here, but
|
||||
* that would mean an asyc call to gethostname, so we don't bother.
|
||||
* @ignore
|
||||
*/
|
||||
var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10);
|
||||
|
||||
// Regular expression that checks for hex value
|
||||
var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
|
||||
|
||||
// Check if buffer exists
|
||||
try {
|
||||
if (Buffer && Buffer.from) {
|
||||
var hasBufferType = true;
|
||||
inspect = require('util').inspect.custom || 'inspect';
|
||||
}
|
||||
} catch (err) {
|
||||
hasBufferType = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new ObjectID instance
|
||||
*
|
||||
* @class
|
||||
* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
|
||||
* @property {number} generationTime The generation time of this ObjectId instance
|
||||
* @return {ObjectID} instance of ObjectID.
|
||||
*/
|
||||
var ObjectID = function ObjectID(id) {
|
||||
// Duck-typing to support ObjectId from different npm packages
|
||||
if (id instanceof ObjectID) return id;
|
||||
if (!(this instanceof ObjectID)) return new ObjectID(id);
|
||||
|
||||
this._bsontype = 'ObjectID';
|
||||
|
||||
// The most common usecase (blank id, new objectId instance)
|
||||
if (id == null || typeof id === 'number') {
|
||||
// Generate a new id
|
||||
this.id = this.generate(id);
|
||||
// If we are caching the hex string
|
||||
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
|
||||
// Return the object
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the passed in id is valid
|
||||
var valid = ObjectID.isValid(id);
|
||||
|
||||
// Throw an error if it's not a valid setup
|
||||
if (!valid && id != null) {
|
||||
throw new Error(
|
||||
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
|
||||
);
|
||||
} else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
|
||||
return new ObjectID(utils.toBuffer(id, 'hex'));
|
||||
} else if (valid && typeof id === 'string' && id.length === 24) {
|
||||
return ObjectID.createFromHexString(id);
|
||||
} else if (id != null && id.length === 12) {
|
||||
// assume 12 byte string
|
||||
this.id = id;
|
||||
} else if (id != null && id.toHexString) {
|
||||
// Duck-typing to support ObjectId from different npm packages
|
||||
return id;
|
||||
} else {
|
||||
throw new Error(
|
||||
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
|
||||
);
|
||||
}
|
||||
|
||||
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
|
||||
};
|
||||
|
||||
// Allow usage of ObjectId as well as ObjectID
|
||||
// var ObjectId = ObjectID;
|
||||
|
||||
// Precomputed hex table enables speedy hex string conversion
|
||||
var hexTable = [];
|
||||
for (var i = 0; i < 256; i++) {
|
||||
hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the ObjectID id as a 24 byte hex string representation
|
||||
*
|
||||
* @method
|
||||
* @return {string} return the 24 byte hex string representation.
|
||||
*/
|
||||
ObjectID.prototype.toHexString = function() {
|
||||
if (ObjectID.cacheHexString && this.__id) return this.__id;
|
||||
|
||||
var hexString = '';
|
||||
if (!this.id || !this.id.length) {
|
||||
throw new Error(
|
||||
'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' +
|
||||
JSON.stringify(this.id) +
|
||||
']'
|
||||
);
|
||||
}
|
||||
|
||||
if (this.id instanceof _Buffer) {
|
||||
hexString = convertToHex(this.id);
|
||||
if (ObjectID.cacheHexString) this.__id = hexString;
|
||||
return hexString;
|
||||
}
|
||||
|
||||
for (var i = 0; i < this.id.length; i++) {
|
||||
hexString += hexTable[this.id.charCodeAt(i)];
|
||||
}
|
||||
|
||||
if (ObjectID.cacheHexString) this.__id = hexString;
|
||||
return hexString;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update the ObjectID index used in generating new ObjectID's on the driver
|
||||
*
|
||||
* @method
|
||||
* @return {number} returns next index value.
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.prototype.get_inc = function() {
|
||||
return (ObjectID.index = (ObjectID.index + 1) % 0xffffff);
|
||||
};
|
||||
|
||||
/**
|
||||
* Update the ObjectID index used in generating new ObjectID's on the driver
|
||||
*
|
||||
* @method
|
||||
* @return {number} returns next index value.
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.prototype.getInc = function() {
|
||||
return this.get_inc();
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate a 12 byte id buffer used in ObjectID's
|
||||
*
|
||||
* @method
|
||||
* @param {number} [time] optional parameter allowing to pass in a second based timestamp.
|
||||
* @return {Buffer} return the 12 byte id buffer string.
|
||||
*/
|
||||
ObjectID.prototype.generate = function(time) {
|
||||
if ('number' !== typeof time) {
|
||||
time = ~~(Date.now() / 1000);
|
||||
}
|
||||
|
||||
// Use pid
|
||||
var pid =
|
||||
(typeof process === 'undefined' || process.pid === 1
|
||||
? Math.floor(Math.random() * 100000)
|
||||
: process.pid) % 0xffff;
|
||||
var inc = this.get_inc();
|
||||
// Buffer used
|
||||
var buffer = utils.allocBuffer(12);
|
||||
// Encode time
|
||||
buffer[3] = time & 0xff;
|
||||
buffer[2] = (time >> 8) & 0xff;
|
||||
buffer[1] = (time >> 16) & 0xff;
|
||||
buffer[0] = (time >> 24) & 0xff;
|
||||
// Encode machine
|
||||
buffer[6] = MACHINE_ID & 0xff;
|
||||
buffer[5] = (MACHINE_ID >> 8) & 0xff;
|
||||
buffer[4] = (MACHINE_ID >> 16) & 0xff;
|
||||
// Encode pid
|
||||
buffer[8] = pid & 0xff;
|
||||
buffer[7] = (pid >> 8) & 0xff;
|
||||
// Encode index
|
||||
buffer[11] = inc & 0xff;
|
||||
buffer[10] = (inc >> 8) & 0xff;
|
||||
buffer[9] = (inc >> 16) & 0xff;
|
||||
// Return the buffer
|
||||
return buffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts the id into a 24 byte hex string for printing
|
||||
*
|
||||
* @param {String} format The Buffer toString format parameter.
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.prototype.toString = function(format) {
|
||||
// Is the id a buffer then use the buffer toString method to return the format
|
||||
if (this.id && this.id.copy) {
|
||||
return this.id.toString(typeof format === 'string' ? format : 'hex');
|
||||
}
|
||||
|
||||
// if(this.buffer )
|
||||
return this.toHexString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts to a string representation of this Id.
|
||||
*
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.prototype[inspect] = ObjectID.prototype.toString;
|
||||
|
||||
/**
|
||||
* Converts to its JSON representation.
|
||||
*
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.prototype.toJSON = function() {
|
||||
return this.toHexString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares the equality of this ObjectID with `otherID`.
|
||||
*
|
||||
* @method
|
||||
* @param {object} otherID ObjectID instance to compare against.
|
||||
* @return {boolean} the result of comparing two ObjectID's
|
||||
*/
|
||||
ObjectID.prototype.equals = function equals(otherId) {
|
||||
// var id;
|
||||
|
||||
if (otherId instanceof ObjectID) {
|
||||
return this.toString() === otherId.toString();
|
||||
} else if (
|
||||
typeof otherId === 'string' &&
|
||||
ObjectID.isValid(otherId) &&
|
||||
otherId.length === 12 &&
|
||||
this.id instanceof _Buffer
|
||||
) {
|
||||
return otherId === this.id.toString('binary');
|
||||
} else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) {
|
||||
return otherId.toLowerCase() === this.toHexString();
|
||||
} else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) {
|
||||
return otherId === this.id;
|
||||
} else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
|
||||
return otherId.toHexString() === this.toHexString();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the generation date (accurate up to the second) that this ID was generated.
|
||||
*
|
||||
* @method
|
||||
* @return {date} the generation date
|
||||
*/
|
||||
ObjectID.prototype.getTimestamp = function() {
|
||||
var timestamp = new Date();
|
||||
var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);
|
||||
timestamp.setTime(Math.floor(time) * 1000);
|
||||
return timestamp;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.index = ~~(Math.random() * 0xffffff);
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
ObjectID.createPk = function createPk() {
|
||||
return new ObjectID();
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
|
||||
*
|
||||
* @method
|
||||
* @param {number} time an integer number representing a number of seconds.
|
||||
* @return {ObjectID} return the created ObjectID
|
||||
*/
|
||||
ObjectID.createFromTime = function createFromTime(time) {
|
||||
var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
// Encode time into first 4 bytes
|
||||
buffer[3] = time & 0xff;
|
||||
buffer[2] = (time >> 8) & 0xff;
|
||||
buffer[1] = (time >> 16) & 0xff;
|
||||
buffer[0] = (time >> 24) & 0xff;
|
||||
// Return the new objectId
|
||||
return new ObjectID(buffer);
|
||||
};
|
||||
|
||||
// Lookup tables
|
||||
//var encodeLookup = '0123456789abcdef'.split('');
|
||||
var decodeLookup = [];
|
||||
i = 0;
|
||||
while (i < 10) decodeLookup[0x30 + i] = i++;
|
||||
while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
|
||||
|
||||
var _Buffer = Buffer;
|
||||
var convertToHex = function(bytes) {
|
||||
return bytes.toString('hex');
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an ObjectID from a hex string representation of an ObjectID.
|
||||
*
|
||||
* @method
|
||||
* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
|
||||
* @return {ObjectID} return the created ObjectID
|
||||
*/
|
||||
ObjectID.createFromHexString = function createFromHexString(string) {
|
||||
// Throw an error if it's not a valid setup
|
||||
if (typeof string === 'undefined' || (string != null && string.length !== 24)) {
|
||||
throw new Error(
|
||||
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
|
||||
);
|
||||
}
|
||||
|
||||
// Use Buffer.from method if available
|
||||
if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex'));
|
||||
|
||||
// Calculate lengths
|
||||
var array = new _Buffer(12);
|
||||
var n = 0;
|
||||
var i = 0;
|
||||
|
||||
while (i < 24) {
|
||||
array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)];
|
||||
}
|
||||
|
||||
return new ObjectID(array);
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if a value is a valid bson ObjectId
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
|
||||
*/
|
||||
ObjectID.isValid = function isValid(id) {
|
||||
if (id == null) return false;
|
||||
|
||||
if (typeof id === 'number') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof id === 'string') {
|
||||
return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
|
||||
}
|
||||
|
||||
if (id instanceof ObjectID) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (id instanceof _Buffer) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Duck-Typing detection of ObjectId like objects
|
||||
if (id.toHexString) {
|
||||
return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(ObjectID.prototype, 'generationTime', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);
|
||||
},
|
||||
set: function(value) {
|
||||
// Encode time into first 4 bytes
|
||||
this.id[3] = value & 0xff;
|
||||
this.id[2] = (value >> 8) & 0xff;
|
||||
this.id[1] = (value >> 16) & 0xff;
|
||||
this.id[0] = (value >> 24) & 0xff;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
module.exports = ObjectID;
|
||||
module.exports.ObjectID = ObjectID;
|
||||
module.exports.ObjectId = ObjectID;
|
||||
-255
@@ -1,255 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var Long = require('../long').Long,
|
||||
Double = require('../double').Double,
|
||||
Timestamp = require('../timestamp').Timestamp,
|
||||
ObjectID = require('../objectid').ObjectID,
|
||||
Symbol = require('../symbol').Symbol,
|
||||
BSONRegExp = require('../regexp').BSONRegExp,
|
||||
Code = require('../code').Code,
|
||||
Decimal128 = require('../decimal128'),
|
||||
MinKey = require('../min_key').MinKey,
|
||||
MaxKey = require('../max_key').MaxKey,
|
||||
DBRef = require('../db_ref').DBRef,
|
||||
Binary = require('../binary').Binary;
|
||||
|
||||
var normalizedFunctionString = require('./utils').normalizedFunctionString;
|
||||
|
||||
// To ensure that 0.4 of node works correctly
|
||||
var isDate = function isDate(d) {
|
||||
return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]';
|
||||
};
|
||||
|
||||
var calculateObjectSize = function calculateObjectSize(
|
||||
object,
|
||||
serializeFunctions,
|
||||
ignoreUndefined
|
||||
) {
|
||||
var totalLength = 4 + 1;
|
||||
|
||||
if (Array.isArray(object)) {
|
||||
for (var i = 0; i < object.length; i++) {
|
||||
totalLength += calculateElement(
|
||||
i.toString(),
|
||||
object[i],
|
||||
serializeFunctions,
|
||||
true,
|
||||
ignoreUndefined
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// If we have toBSON defined, override the current object
|
||||
if (object.toBSON) {
|
||||
object = object.toBSON();
|
||||
}
|
||||
|
||||
// Calculate size
|
||||
for (var key in object) {
|
||||
totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
|
||||
}
|
||||
}
|
||||
|
||||
return totalLength;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) {
|
||||
// If we have toBSON defined, override the current object
|
||||
if (value && value.toBSON) {
|
||||
value = value.toBSON();
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1;
|
||||
case 'number':
|
||||
if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {
|
||||
if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) {
|
||||
// 32 bit
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
|
||||
} else {
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
|
||||
}
|
||||
} else {
|
||||
// 64 bit
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
|
||||
}
|
||||
case 'undefined':
|
||||
if (isArray || !ignoreUndefined)
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
|
||||
return 0;
|
||||
case 'boolean':
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
|
||||
case 'object':
|
||||
if (
|
||||
value == null ||
|
||||
value instanceof MinKey ||
|
||||
value instanceof MaxKey ||
|
||||
value['_bsontype'] === 'MinKey' ||
|
||||
value['_bsontype'] === 'MaxKey'
|
||||
) {
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
|
||||
} else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') {
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
|
||||
} else if (value instanceof Date || isDate(value)) {
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
|
||||
} else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length
|
||||
);
|
||||
} else if (
|
||||
value instanceof Long ||
|
||||
value instanceof Double ||
|
||||
value instanceof Timestamp ||
|
||||
value['_bsontype'] === 'Long' ||
|
||||
value['_bsontype'] === 'Double' ||
|
||||
value['_bsontype'] === 'Timestamp'
|
||||
) {
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
|
||||
} else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') {
|
||||
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
|
||||
} else if (value instanceof Code || value['_bsontype'] === 'Code') {
|
||||
// Calculate size depending on the availability of a scope
|
||||
if (value.scope != null && Object.keys(value.scope).length > 0) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
4 +
|
||||
4 +
|
||||
Buffer.byteLength(value.code.toString(), 'utf8') +
|
||||
1 +
|
||||
calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
4 +
|
||||
Buffer.byteLength(value.code.toString(), 'utf8') +
|
||||
1
|
||||
);
|
||||
}
|
||||
} else if (value instanceof Binary || value['_bsontype'] === 'Binary') {
|
||||
// Check what kind of subtype we have
|
||||
if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
(value.position + 1 + 4 + 1 + 4)
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)
|
||||
);
|
||||
}
|
||||
} else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
Buffer.byteLength(value.value, 'utf8') +
|
||||
4 +
|
||||
1 +
|
||||
1
|
||||
);
|
||||
} else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') {
|
||||
// Set up correct object for serialization
|
||||
var ordered_values = {
|
||||
$ref: value.namespace,
|
||||
$id: value.oid
|
||||
};
|
||||
|
||||
// Add db reference if it exists
|
||||
if (null != value.db) {
|
||||
ordered_values['$db'] = value.db;
|
||||
}
|
||||
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)
|
||||
);
|
||||
} else if (
|
||||
value instanceof RegExp ||
|
||||
Object.prototype.toString.call(value) === '[object RegExp]'
|
||||
) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
Buffer.byteLength(value.source, 'utf8') +
|
||||
1 +
|
||||
(value.global ? 1 : 0) +
|
||||
(value.ignoreCase ? 1 : 0) +
|
||||
(value.multiline ? 1 : 0) +
|
||||
1
|
||||
);
|
||||
} else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
Buffer.byteLength(value.pattern, 'utf8') +
|
||||
1 +
|
||||
Buffer.byteLength(value.options, 'utf8') +
|
||||
1
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
calculateObjectSize(value, serializeFunctions, ignoreUndefined) +
|
||||
1
|
||||
);
|
||||
}
|
||||
case 'function':
|
||||
// WTF for 0.4.X where typeof /someregexp/ === 'function'
|
||||
if (
|
||||
value instanceof RegExp ||
|
||||
Object.prototype.toString.call(value) === '[object RegExp]' ||
|
||||
String.call(value) === '[object RegExp]'
|
||||
) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
Buffer.byteLength(value.source, 'utf8') +
|
||||
1 +
|
||||
(value.global ? 1 : 0) +
|
||||
(value.ignoreCase ? 1 : 0) +
|
||||
(value.multiline ? 1 : 0) +
|
||||
1
|
||||
);
|
||||
} else {
|
||||
if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
4 +
|
||||
4 +
|
||||
Buffer.byteLength(normalizedFunctionString(value), 'utf8') +
|
||||
1 +
|
||||
calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)
|
||||
);
|
||||
} else if (serializeFunctions) {
|
||||
return (
|
||||
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
|
||||
1 +
|
||||
4 +
|
||||
Buffer.byteLength(normalizedFunctionString(value), 'utf8') +
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
var BSON = {};
|
||||
|
||||
// BSON MAX VALUES
|
||||
BSON.BSON_INT32_MAX = 0x7fffffff;
|
||||
BSON.BSON_INT32_MIN = -0x80000000;
|
||||
|
||||
// JS MAX PRECISE VALUES
|
||||
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
||||
module.exports = calculateObjectSize;
|
||||
-782
@@ -1,782 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var Long = require('../long').Long,
|
||||
Double = require('../double').Double,
|
||||
Timestamp = require('../timestamp').Timestamp,
|
||||
ObjectID = require('../objectid').ObjectID,
|
||||
Symbol = require('../symbol').Symbol,
|
||||
Code = require('../code').Code,
|
||||
MinKey = require('../min_key').MinKey,
|
||||
MaxKey = require('../max_key').MaxKey,
|
||||
Decimal128 = require('../decimal128'),
|
||||
Int32 = require('../int_32'),
|
||||
DBRef = require('../db_ref').DBRef,
|
||||
BSONRegExp = require('../regexp').BSONRegExp,
|
||||
Binary = require('../binary').Binary;
|
||||
|
||||
var utils = require('./utils');
|
||||
|
||||
var deserialize = function(buffer, options, isArray) {
|
||||
options = options == null ? {} : options;
|
||||
var index = options && options.index ? options.index : 0;
|
||||
// Read the document size
|
||||
var size =
|
||||
buffer[index] |
|
||||
(buffer[index + 1] << 8) |
|
||||
(buffer[index + 2] << 16) |
|
||||
(buffer[index + 3] << 24);
|
||||
|
||||
// Ensure buffer is valid size
|
||||
if (size < 5 || buffer.length < size || size + index > buffer.length) {
|
||||
throw new Error('corrupt bson message');
|
||||
}
|
||||
|
||||
// Illegal end value
|
||||
if (buffer[index + size - 1] !== 0) {
|
||||
throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
|
||||
}
|
||||
|
||||
// Start deserializtion
|
||||
return deserializeObject(buffer, index, options, isArray);
|
||||
};
|
||||
|
||||
var deserializeObject = function(buffer, index, options, isArray) {
|
||||
var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
|
||||
var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
|
||||
var cacheFunctionsCrc32 =
|
||||
options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32'];
|
||||
|
||||
if (!cacheFunctionsCrc32) var crc32 = null;
|
||||
|
||||
var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
|
||||
|
||||
// Return raw bson buffer instead of parsing it
|
||||
var raw = options['raw'] == null ? false : options['raw'];
|
||||
|
||||
// Return BSONRegExp objects instead of native regular expressions
|
||||
var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
|
||||
|
||||
// Controls the promotion of values vs wrapper classes
|
||||
var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
|
||||
var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
|
||||
var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
|
||||
|
||||
// Set the start index
|
||||
var startIndex = index;
|
||||
|
||||
// Validate that we have at least 4 bytes of buffer
|
||||
if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long');
|
||||
|
||||
// Read the document size
|
||||
var size =
|
||||
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
|
||||
|
||||
// Ensure buffer is valid size
|
||||
if (size < 5 || size > buffer.length) throw new Error('corrupt bson message');
|
||||
|
||||
// Create holding object
|
||||
var object = isArray ? [] : {};
|
||||
// Used for arrays to skip having to perform utf8 decoding
|
||||
var arrayIndex = 0;
|
||||
|
||||
var done = false;
|
||||
|
||||
// While we have more left data left keep parsing
|
||||
// while (buffer[index + 1] !== 0) {
|
||||
while (!done) {
|
||||
// Read the type
|
||||
var elementType = buffer[index++];
|
||||
// If we get a zero it's the last byte, exit
|
||||
if (elementType === 0) break;
|
||||
|
||||
// Get the start search index
|
||||
var i = index;
|
||||
// Locate the end of the c string
|
||||
while (buffer[i] !== 0x00 && i < buffer.length) {
|
||||
i++;
|
||||
}
|
||||
|
||||
// If are at the end of the buffer there is a problem with the document
|
||||
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');
|
||||
var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
|
||||
|
||||
index = i + 1;
|
||||
|
||||
if (elementType === BSON.BSON_DATA_STRING) {
|
||||
var stringSize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
if (
|
||||
stringSize <= 0 ||
|
||||
stringSize > buffer.length - index ||
|
||||
buffer[index + stringSize - 1] !== 0
|
||||
)
|
||||
throw new Error('bad string length in bson');
|
||||
object[name] = buffer.toString('utf8', index, index + stringSize - 1);
|
||||
index = index + stringSize;
|
||||
} else if (elementType === BSON.BSON_DATA_OID) {
|
||||
var oid = utils.allocBuffer(12);
|
||||
buffer.copy(oid, 0, index, index + 12);
|
||||
object[name] = new ObjectID(oid);
|
||||
index = index + 12;
|
||||
} else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) {
|
||||
object[name] = new Int32(
|
||||
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)
|
||||
);
|
||||
} else if (elementType === BSON.BSON_DATA_INT) {
|
||||
object[name] =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
} else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) {
|
||||
object[name] = new Double(buffer.readDoubleLE(index));
|
||||
index = index + 8;
|
||||
} else if (elementType === BSON.BSON_DATA_NUMBER) {
|
||||
object[name] = buffer.readDoubleLE(index);
|
||||
index = index + 8;
|
||||
} else if (elementType === BSON.BSON_DATA_DATE) {
|
||||
var lowBits =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
var highBits =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
object[name] = new Date(new Long(lowBits, highBits).toNumber());
|
||||
} else if (elementType === BSON.BSON_DATA_BOOLEAN) {
|
||||
if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value');
|
||||
object[name] = buffer[index++] === 1;
|
||||
} else if (elementType === BSON.BSON_DATA_OBJECT) {
|
||||
var _index = index;
|
||||
var objectSize =
|
||||
buffer[index] |
|
||||
(buffer[index + 1] << 8) |
|
||||
(buffer[index + 2] << 16) |
|
||||
(buffer[index + 3] << 24);
|
||||
if (objectSize <= 0 || objectSize > buffer.length - index)
|
||||
throw new Error('bad embedded document length in bson');
|
||||
|
||||
// We have a raw value
|
||||
if (raw) {
|
||||
object[name] = buffer.slice(index, index + objectSize);
|
||||
} else {
|
||||
object[name] = deserializeObject(buffer, _index, options, false);
|
||||
}
|
||||
|
||||
index = index + objectSize;
|
||||
} else if (elementType === BSON.BSON_DATA_ARRAY) {
|
||||
_index = index;
|
||||
objectSize =
|
||||
buffer[index] |
|
||||
(buffer[index + 1] << 8) |
|
||||
(buffer[index + 2] << 16) |
|
||||
(buffer[index + 3] << 24);
|
||||
var arrayOptions = options;
|
||||
|
||||
// Stop index
|
||||
var stopIndex = index + objectSize;
|
||||
|
||||
// All elements of array to be returned as raw bson
|
||||
if (fieldsAsRaw && fieldsAsRaw[name]) {
|
||||
arrayOptions = {};
|
||||
for (var n in options) arrayOptions[n] = options[n];
|
||||
arrayOptions['raw'] = true;
|
||||
}
|
||||
|
||||
object[name] = deserializeObject(buffer, _index, arrayOptions, true);
|
||||
index = index + objectSize;
|
||||
|
||||
if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte');
|
||||
if (index !== stopIndex) throw new Error('corrupted array bson');
|
||||
} else if (elementType === BSON.BSON_DATA_UNDEFINED) {
|
||||
object[name] = undefined;
|
||||
} else if (elementType === BSON.BSON_DATA_NULL) {
|
||||
object[name] = null;
|
||||
} else if (elementType === BSON.BSON_DATA_LONG) {
|
||||
// Unpack the low and high bits
|
||||
lowBits =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
highBits =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
var long = new Long(lowBits, highBits);
|
||||
// Promote the long if possible
|
||||
if (promoteLongs && promoteValues === true) {
|
||||
object[name] =
|
||||
long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
|
||||
? long.toNumber()
|
||||
: long;
|
||||
} else {
|
||||
object[name] = long;
|
||||
}
|
||||
} else if (elementType === BSON.BSON_DATA_DECIMAL128) {
|
||||
// Buffer to contain the decimal bytes
|
||||
var bytes = utils.allocBuffer(16);
|
||||
// Copy the next 16 bytes into the bytes buffer
|
||||
buffer.copy(bytes, 0, index, index + 16);
|
||||
// Update index
|
||||
index = index + 16;
|
||||
// Assign the new Decimal128 value
|
||||
var decimal128 = new Decimal128(bytes);
|
||||
// If we have an alternative mapper use that
|
||||
object[name] = decimal128.toObject ? decimal128.toObject() : decimal128;
|
||||
} else if (elementType === BSON.BSON_DATA_BINARY) {
|
||||
var binarySize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
var totalBinarySize = binarySize;
|
||||
var subType = buffer[index++];
|
||||
|
||||
// Did we have a negative binary size, throw
|
||||
if (binarySize < 0) throw new Error('Negative binary type element size found');
|
||||
|
||||
// Is the length longer than the document
|
||||
if (binarySize > buffer.length) throw new Error('Binary type size larger than document size');
|
||||
|
||||
// Decode as raw Buffer object if options specifies it
|
||||
if (buffer['slice'] != null) {
|
||||
// If we have subtype 2 skip the 4 bytes for the size
|
||||
if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
|
||||
binarySize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
if (binarySize < 0)
|
||||
throw new Error('Negative binary type element size found for subtype 0x02');
|
||||
if (binarySize > totalBinarySize - 4)
|
||||
throw new Error('Binary type with subtype 0x02 contains to long binary size');
|
||||
if (binarySize < totalBinarySize - 4)
|
||||
throw new Error('Binary type with subtype 0x02 contains to short binary size');
|
||||
}
|
||||
|
||||
if (promoteBuffers && promoteValues) {
|
||||
object[name] = buffer.slice(index, index + binarySize);
|
||||
} else {
|
||||
object[name] = new Binary(buffer.slice(index, index + binarySize), subType);
|
||||
}
|
||||
} else {
|
||||
var _buffer =
|
||||
typeof Uint8Array !== 'undefined'
|
||||
? new Uint8Array(new ArrayBuffer(binarySize))
|
||||
: new Array(binarySize);
|
||||
// If we have subtype 2 skip the 4 bytes for the size
|
||||
if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
|
||||
binarySize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
if (binarySize < 0)
|
||||
throw new Error('Negative binary type element size found for subtype 0x02');
|
||||
if (binarySize > totalBinarySize - 4)
|
||||
throw new Error('Binary type with subtype 0x02 contains to long binary size');
|
||||
if (binarySize < totalBinarySize - 4)
|
||||
throw new Error('Binary type with subtype 0x02 contains to short binary size');
|
||||
}
|
||||
|
||||
// Copy the data
|
||||
for (i = 0; i < binarySize; i++) {
|
||||
_buffer[i] = buffer[index + i];
|
||||
}
|
||||
|
||||
if (promoteBuffers && promoteValues) {
|
||||
object[name] = _buffer;
|
||||
} else {
|
||||
object[name] = new Binary(_buffer, subType);
|
||||
}
|
||||
}
|
||||
|
||||
// Update the index
|
||||
index = index + binarySize;
|
||||
} else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) {
|
||||
// Get the start search index
|
||||
i = index;
|
||||
// Locate the end of the c string
|
||||
while (buffer[i] !== 0x00 && i < buffer.length) {
|
||||
i++;
|
||||
}
|
||||
// If are at the end of the buffer there is a problem with the document
|
||||
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');
|
||||
// Return the C string
|
||||
var source = buffer.toString('utf8', index, i);
|
||||
// Create the regexp
|
||||
index = i + 1;
|
||||
|
||||
// Get the start search index
|
||||
i = index;
|
||||
// Locate the end of the c string
|
||||
while (buffer[i] !== 0x00 && i < buffer.length) {
|
||||
i++;
|
||||
}
|
||||
// If are at the end of the buffer there is a problem with the document
|
||||
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');
|
||||
// Return the C string
|
||||
var regExpOptions = buffer.toString('utf8', index, i);
|
||||
index = i + 1;
|
||||
|
||||
// For each option add the corresponding one for javascript
|
||||
var optionsArray = new Array(regExpOptions.length);
|
||||
|
||||
// Parse options
|
||||
for (i = 0; i < regExpOptions.length; i++) {
|
||||
switch (regExpOptions[i]) {
|
||||
case 'm':
|
||||
optionsArray[i] = 'm';
|
||||
break;
|
||||
case 's':
|
||||
optionsArray[i] = 'g';
|
||||
break;
|
||||
case 'i':
|
||||
optionsArray[i] = 'i';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
object[name] = new RegExp(source, optionsArray.join(''));
|
||||
} else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) {
|
||||
// Get the start search index
|
||||
i = index;
|
||||
// Locate the end of the c string
|
||||
while (buffer[i] !== 0x00 && i < buffer.length) {
|
||||
i++;
|
||||
}
|
||||
// If are at the end of the buffer there is a problem with the document
|
||||
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');
|
||||
// Return the C string
|
||||
source = buffer.toString('utf8', index, i);
|
||||
index = i + 1;
|
||||
|
||||
// Get the start search index
|
||||
i = index;
|
||||
// Locate the end of the c string
|
||||
while (buffer[i] !== 0x00 && i < buffer.length) {
|
||||
i++;
|
||||
}
|
||||
// If are at the end of the buffer there is a problem with the document
|
||||
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString');
|
||||
// Return the C string
|
||||
regExpOptions = buffer.toString('utf8', index, i);
|
||||
index = i + 1;
|
||||
|
||||
// Set the object
|
||||
object[name] = new BSONRegExp(source, regExpOptions);
|
||||
} else if (elementType === BSON.BSON_DATA_SYMBOL) {
|
||||
stringSize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
if (
|
||||
stringSize <= 0 ||
|
||||
stringSize > buffer.length - index ||
|
||||
buffer[index + stringSize - 1] !== 0
|
||||
)
|
||||
throw new Error('bad string length in bson');
|
||||
object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1));
|
||||
index = index + stringSize;
|
||||
} else if (elementType === BSON.BSON_DATA_TIMESTAMP) {
|
||||
lowBits =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
highBits =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
object[name] = new Timestamp(lowBits, highBits);
|
||||
} else if (elementType === BSON.BSON_DATA_MIN_KEY) {
|
||||
object[name] = new MinKey();
|
||||
} else if (elementType === BSON.BSON_DATA_MAX_KEY) {
|
||||
object[name] = new MaxKey();
|
||||
} else if (elementType === BSON.BSON_DATA_CODE) {
|
||||
stringSize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
if (
|
||||
stringSize <= 0 ||
|
||||
stringSize > buffer.length - index ||
|
||||
buffer[index + stringSize - 1] !== 0
|
||||
)
|
||||
throw new Error('bad string length in bson');
|
||||
var functionString = buffer.toString('utf8', index, index + stringSize - 1);
|
||||
|
||||
// If we are evaluating the functions
|
||||
if (evalFunctions) {
|
||||
// If we have cache enabled let's look for the md5 of the function in the cache
|
||||
if (cacheFunctions) {
|
||||
var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString;
|
||||
// Got to do this to avoid V8 deoptimizing the call due to finding eval
|
||||
object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);
|
||||
} else {
|
||||
object[name] = isolateEval(functionString);
|
||||
}
|
||||
} else {
|
||||
object[name] = new Code(functionString);
|
||||
}
|
||||
|
||||
// Update parse index position
|
||||
index = index + stringSize;
|
||||
} else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) {
|
||||
var totalSize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
|
||||
// Element cannot be shorter than totalSize + stringSize + documentSize + terminator
|
||||
if (totalSize < 4 + 4 + 4 + 1) {
|
||||
throw new Error('code_w_scope total size shorter minimum expected length');
|
||||
}
|
||||
|
||||
// Get the code string size
|
||||
stringSize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
// Check if we have a valid string
|
||||
if (
|
||||
stringSize <= 0 ||
|
||||
stringSize > buffer.length - index ||
|
||||
buffer[index + stringSize - 1] !== 0
|
||||
)
|
||||
throw new Error('bad string length in bson');
|
||||
|
||||
// Javascript function
|
||||
functionString = buffer.toString('utf8', index, index + stringSize - 1);
|
||||
// Update parse index position
|
||||
index = index + stringSize;
|
||||
// Parse the element
|
||||
_index = index;
|
||||
// Decode the size of the object document
|
||||
objectSize =
|
||||
buffer[index] |
|
||||
(buffer[index + 1] << 8) |
|
||||
(buffer[index + 2] << 16) |
|
||||
(buffer[index + 3] << 24);
|
||||
// Decode the scope object
|
||||
var scopeObject = deserializeObject(buffer, _index, options, false);
|
||||
// Adjust the index
|
||||
index = index + objectSize;
|
||||
|
||||
// Check if field length is to short
|
||||
if (totalSize < 4 + 4 + objectSize + stringSize) {
|
||||
throw new Error('code_w_scope total size is to short, truncating scope');
|
||||
}
|
||||
|
||||
// Check if totalSize field is to long
|
||||
if (totalSize > 4 + 4 + objectSize + stringSize) {
|
||||
throw new Error('code_w_scope total size is to long, clips outer document');
|
||||
}
|
||||
|
||||
// If we are evaluating the functions
|
||||
if (evalFunctions) {
|
||||
// If we have cache enabled let's look for the md5 of the function in the cache
|
||||
if (cacheFunctions) {
|
||||
hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString;
|
||||
// Got to do this to avoid V8 deoptimizing the call due to finding eval
|
||||
object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);
|
||||
} else {
|
||||
object[name] = isolateEval(functionString);
|
||||
}
|
||||
|
||||
object[name].scope = scopeObject;
|
||||
} else {
|
||||
object[name] = new Code(functionString, scopeObject);
|
||||
}
|
||||
} else if (elementType === BSON.BSON_DATA_DBPOINTER) {
|
||||
// Get the code string size
|
||||
stringSize =
|
||||
buffer[index++] |
|
||||
(buffer[index++] << 8) |
|
||||
(buffer[index++] << 16) |
|
||||
(buffer[index++] << 24);
|
||||
// Check if we have a valid string
|
||||
if (
|
||||
stringSize <= 0 ||
|
||||
stringSize > buffer.length - index ||
|
||||
buffer[index + stringSize - 1] !== 0
|
||||
)
|
||||
throw new Error('bad string length in bson');
|
||||
// Namespace
|
||||
var namespace = buffer.toString('utf8', index, index + stringSize - 1);
|
||||
// Update parse index position
|
||||
index = index + stringSize;
|
||||
|
||||
// Read the oid
|
||||
var oidBuffer = utils.allocBuffer(12);
|
||||
buffer.copy(oidBuffer, 0, index, index + 12);
|
||||
oid = new ObjectID(oidBuffer);
|
||||
|
||||
// Update the index
|
||||
index = index + 12;
|
||||
|
||||
// Split the namespace
|
||||
var parts = namespace.split('.');
|
||||
var db = parts.shift();
|
||||
var collection = parts.join('.');
|
||||
// Upgrade to DBRef type
|
||||
object[name] = new DBRef(collection, oid, db);
|
||||
} else {
|
||||
throw new Error(
|
||||
'Detected unknown BSON type ' +
|
||||
elementType.toString(16) +
|
||||
' for fieldname "' +
|
||||
name +
|
||||
'", are you using the latest BSON parser'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the deserialization was against a valid array/object
|
||||
if (size !== index - startIndex) {
|
||||
if (isArray) throw new Error('corrupt array bson');
|
||||
throw new Error('corrupt object bson');
|
||||
}
|
||||
|
||||
// Check if we have a db ref object
|
||||
if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);
|
||||
return object;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ensure eval is isolated.
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var isolateEvalWithHash = function(functionCache, hash, functionString, object) {
|
||||
// Contains the value we are going to set
|
||||
var value = null;
|
||||
|
||||
// Check for cache hit, eval if missing and return cached function
|
||||
if (functionCache[hash] == null) {
|
||||
eval('value = ' + functionString);
|
||||
functionCache[hash] = value;
|
||||
}
|
||||
// Set the object
|
||||
return functionCache[hash].bind(object);
|
||||
};
|
||||
|
||||
/**
|
||||
* Ensure eval is isolated.
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var isolateEval = function(functionString) {
|
||||
// Contains the value we are going to set
|
||||
var value = null;
|
||||
// Eval the function
|
||||
eval('value = ' + functionString);
|
||||
return value;
|
||||
};
|
||||
|
||||
var BSON = {};
|
||||
|
||||
/**
|
||||
* Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var functionCache = (BSON.functionCache = {});
|
||||
|
||||
/**
|
||||
* Number BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_NUMBER
|
||||
**/
|
||||
BSON.BSON_DATA_NUMBER = 1;
|
||||
/**
|
||||
* String BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_STRING
|
||||
**/
|
||||
BSON.BSON_DATA_STRING = 2;
|
||||
/**
|
||||
* Object BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_OBJECT
|
||||
**/
|
||||
BSON.BSON_DATA_OBJECT = 3;
|
||||
/**
|
||||
* Array BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_ARRAY
|
||||
**/
|
||||
BSON.BSON_DATA_ARRAY = 4;
|
||||
/**
|
||||
* Binary BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_BINARY
|
||||
**/
|
||||
BSON.BSON_DATA_BINARY = 5;
|
||||
/**
|
||||
* Binary BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_UNDEFINED
|
||||
**/
|
||||
BSON.BSON_DATA_UNDEFINED = 6;
|
||||
/**
|
||||
* ObjectID BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_OID
|
||||
**/
|
||||
BSON.BSON_DATA_OID = 7;
|
||||
/**
|
||||
* Boolean BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_BOOLEAN
|
||||
**/
|
||||
BSON.BSON_DATA_BOOLEAN = 8;
|
||||
/**
|
||||
* Date BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_DATE
|
||||
**/
|
||||
BSON.BSON_DATA_DATE = 9;
|
||||
/**
|
||||
* null BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_NULL
|
||||
**/
|
||||
BSON.BSON_DATA_NULL = 10;
|
||||
/**
|
||||
* RegExp BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_REGEXP
|
||||
**/
|
||||
BSON.BSON_DATA_REGEXP = 11;
|
||||
/**
|
||||
* Code BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_DBPOINTER
|
||||
**/
|
||||
BSON.BSON_DATA_DBPOINTER = 12;
|
||||
/**
|
||||
* Code BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_CODE
|
||||
**/
|
||||
BSON.BSON_DATA_CODE = 13;
|
||||
/**
|
||||
* Symbol BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_SYMBOL
|
||||
**/
|
||||
BSON.BSON_DATA_SYMBOL = 14;
|
||||
/**
|
||||
* Code with Scope BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_CODE_W_SCOPE
|
||||
**/
|
||||
BSON.BSON_DATA_CODE_W_SCOPE = 15;
|
||||
/**
|
||||
* 32 bit Integer BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_INT
|
||||
**/
|
||||
BSON.BSON_DATA_INT = 16;
|
||||
/**
|
||||
* Timestamp BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_TIMESTAMP
|
||||
**/
|
||||
BSON.BSON_DATA_TIMESTAMP = 17;
|
||||
/**
|
||||
* Long BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_LONG
|
||||
**/
|
||||
BSON.BSON_DATA_LONG = 18;
|
||||
/**
|
||||
* Long BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_DECIMAL128
|
||||
**/
|
||||
BSON.BSON_DATA_DECIMAL128 = 19;
|
||||
/**
|
||||
* MinKey BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_MIN_KEY
|
||||
**/
|
||||
BSON.BSON_DATA_MIN_KEY = 0xff;
|
||||
/**
|
||||
* MaxKey BSON Type
|
||||
*
|
||||
* @classconstant BSON_DATA_MAX_KEY
|
||||
**/
|
||||
BSON.BSON_DATA_MAX_KEY = 0x7f;
|
||||
|
||||
/**
|
||||
* Binary Default Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_DEFAULT
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
/**
|
||||
* Binary Function Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_FUNCTION
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
/**
|
||||
* Binary Byte Array Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
/**
|
||||
* Binary UUID Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_UUID
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
/**
|
||||
* Binary MD5 Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_MD5
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
/**
|
||||
* Binary User Defined Type
|
||||
*
|
||||
* @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
|
||||
**/
|
||||
BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
// BSON MAX VALUES
|
||||
BSON.BSON_INT32_MAX = 0x7fffffff;
|
||||
BSON.BSON_INT32_MIN = -0x80000000;
|
||||
|
||||
BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;
|
||||
BSON.BSON_INT64_MIN = -Math.pow(2, 63);
|
||||
|
||||
// JS MAX PRECISE VALUES
|
||||
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
||||
// Internal long versions
|
||||
var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.
|
||||
var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
||||
module.exports = deserialize;
|
||||
-1182
File diff suppressed because it is too large
Load Diff
-28
@@ -1,28 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Normalizes our expected stringified form of a function across versions of node
|
||||
* @param {Function} fn The function to stringify
|
||||
*/
|
||||
function normalizedFunctionString(fn) {
|
||||
return fn.toString().replace(/function *\(/, 'function (');
|
||||
}
|
||||
|
||||
function newBuffer(item, encoding) {
|
||||
return new Buffer(item, encoding);
|
||||
}
|
||||
|
||||
function allocBuffer() {
|
||||
return Buffer.alloc.apply(Buffer, arguments);
|
||||
}
|
||||
|
||||
function toBuffer() {
|
||||
return Buffer.from.apply(Buffer, arguments);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizedFunctionString: normalizedFunctionString,
|
||||
allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer,
|
||||
toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer
|
||||
};
|
||||
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* A class representation of the BSON RegExp type.
|
||||
*
|
||||
* @class
|
||||
* @return {BSONRegExp} A MinKey instance
|
||||
*/
|
||||
function BSONRegExp(pattern, options) {
|
||||
if (!(this instanceof BSONRegExp)) return new BSONRegExp();
|
||||
|
||||
// Execute
|
||||
this._bsontype = 'BSONRegExp';
|
||||
this.pattern = pattern || '';
|
||||
this.options = options || '';
|
||||
|
||||
// Validate options
|
||||
for (var i = 0; i < this.options.length; i++) {
|
||||
if (
|
||||
!(
|
||||
this.options[i] === 'i' ||
|
||||
this.options[i] === 'm' ||
|
||||
this.options[i] === 'x' ||
|
||||
this.options[i] === 'l' ||
|
||||
this.options[i] === 's' ||
|
||||
this.options[i] === 'u'
|
||||
)
|
||||
) {
|
||||
throw new Error('the regular expression options [' + this.options[i] + '] is not supported');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BSONRegExp;
|
||||
module.exports.BSONRegExp = BSONRegExp;
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
// Custom inspect property name / symbol.
|
||||
var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect';
|
||||
|
||||
/**
|
||||
* A class representation of the BSON Symbol type.
|
||||
*
|
||||
* @class
|
||||
* @deprecated
|
||||
* @param {string} value the string representing the symbol.
|
||||
* @return {Symbol}
|
||||
*/
|
||||
function Symbol(value) {
|
||||
if (!(this instanceof Symbol)) return new Symbol(value);
|
||||
this._bsontype = 'Symbol';
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access the wrapped string value.
|
||||
*
|
||||
* @method
|
||||
* @return {String} returns the wrapped string.
|
||||
*/
|
||||
Symbol.prototype.valueOf = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Symbol.prototype.toString = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Symbol.prototype[inspect] = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Symbol.prototype.toJSON = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
module.exports = Symbol;
|
||||
module.exports.Symbol = Symbol;
|
||||
-854
@@ -1,854 +0,0 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright 2009 Google Inc. All Rights Reserved
|
||||
|
||||
/**
|
||||
* This type is for INTERNAL use in MongoDB only and should not be used in applications.
|
||||
* The appropriate corresponding type is the JavaScript Date type.
|
||||
*
|
||||
* Defines a Timestamp class for representing a 64-bit two's-complement
|
||||
* integer value, which faithfully simulates the behavior of a Java "Timestamp". This
|
||||
* implementation is derived from TimestampLib in GWT.
|
||||
*
|
||||
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
|
||||
* values as *signed* integers. See the from* functions below for more
|
||||
* convenient ways of constructing Timestamps.
|
||||
*
|
||||
* The internal representation of a Timestamp is the two given signed, 32-bit values.
|
||||
* We use 32-bit pieces because these are the size of integers on which
|
||||
* Javascript performs bit-operations. For operations like addition and
|
||||
* multiplication, we split each number into 16-bit pieces, which can easily be
|
||||
* multiplied within Javascript's floating-point representation without overflow
|
||||
* or change in sign.
|
||||
*
|
||||
* In the algorithms below, we frequently reduce the negative case to the
|
||||
* positive case by negating the input(s) and then post-processing the result.
|
||||
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
|
||||
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
|
||||
* a positive number, it overflows back into a negative). Not handling this
|
||||
* case would often result in infinite recursion.
|
||||
*
|
||||
* @class
|
||||
* @param {number} low the low (signed) 32 bits of the Timestamp.
|
||||
* @param {number} high the high (signed) 32 bits of the Timestamp.
|
||||
*/
|
||||
function Timestamp(low, high) {
|
||||
if (!(this instanceof Timestamp)) return new Timestamp(low, high);
|
||||
this._bsontype = 'Timestamp';
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
this.high_ = high | 0; // force into 32 signed bits.
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the int value.
|
||||
*
|
||||
* @return {number} the value, assuming it is a 32-bit integer.
|
||||
*/
|
||||
Timestamp.prototype.toInt = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the Number value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the closest floating-point representation to this value.
|
||||
*/
|
||||
Timestamp.prototype.toNumber = function() {
|
||||
return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the JSON value.
|
||||
*
|
||||
* @method
|
||||
* @return {string} the JSON representation.
|
||||
*/
|
||||
Timestamp.prototype.toJSON = function() {
|
||||
return this.toString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the String value.
|
||||
*
|
||||
* @method
|
||||
* @param {number} [opt_radix] the radix in which the text should be written.
|
||||
* @return {string} the textual representation of this value.
|
||||
*/
|
||||
Timestamp.prototype.toString = function(opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (this.isZero()) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
// We need to change the Timestamp value before it can be negated, so we remove
|
||||
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
var radixTimestamp = Timestamp.fromNumber(radix);
|
||||
var div = this.div(radixTimestamp);
|
||||
var rem = div.multiply(radixTimestamp).subtract(this);
|
||||
return div.toString(radix) + rem.toInt().toString(radix);
|
||||
} else {
|
||||
return '-' + this.negate().toString(radix);
|
||||
}
|
||||
}
|
||||
|
||||
// Do several (6) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6));
|
||||
|
||||
rem = this;
|
||||
var result = '';
|
||||
|
||||
while (!rem.isZero()) {
|
||||
var remDiv = rem.div(radixToPower);
|
||||
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
|
||||
var digits = intval.toString(radix);
|
||||
|
||||
rem = remDiv;
|
||||
if (rem.isZero()) {
|
||||
return digits + result;
|
||||
} else {
|
||||
while (digits.length < 6) {
|
||||
digits = '0' + digits;
|
||||
}
|
||||
result = '' + digits + result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the high 32-bits value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the high 32-bits as a signed value.
|
||||
*/
|
||||
Timestamp.prototype.getHighBits = function() {
|
||||
return this.high_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low 32-bits value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the low 32-bits as a signed value.
|
||||
*/
|
||||
Timestamp.prototype.getLowBits = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low unsigned 32-bits value.
|
||||
*
|
||||
* @method
|
||||
* @return {number} the low 32-bits as an unsigned value.
|
||||
*/
|
||||
Timestamp.prototype.getLowBitsUnsigned = function() {
|
||||
return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the number of bits needed to represent the absolute value of this Timestamp.
|
||||
*
|
||||
* @method
|
||||
* @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp.
|
||||
*/
|
||||
Timestamp.prototype.getNumBitsAbs = function() {
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
return 64;
|
||||
} else {
|
||||
return this.negate().getNumBitsAbs();
|
||||
}
|
||||
} else {
|
||||
var val = this.high_ !== 0 ? this.high_ : this.low_;
|
||||
for (var bit = 31; bit > 0; bit--) {
|
||||
if ((val & (1 << bit)) !== 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return this.high_ !== 0 ? bit + 33 : bit + 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is zero.
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} whether this value is zero.
|
||||
*/
|
||||
Timestamp.prototype.isZero = function() {
|
||||
return this.high_ === 0 && this.low_ === 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is negative.
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} whether this value is negative.
|
||||
*/
|
||||
Timestamp.prototype.isNegative = function() {
|
||||
return this.high_ < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is odd.
|
||||
*
|
||||
* @method
|
||||
* @return {boolean} whether this value is odd.
|
||||
*/
|
||||
Timestamp.prototype.isOdd = function() {
|
||||
return (this.low_ & 1) === 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp equals the other
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} whether this Timestamp equals the other
|
||||
*/
|
||||
Timestamp.prototype.equals = function(other) {
|
||||
return this.high_ === other.high_ && this.low_ === other.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp does not equal the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} whether this Timestamp does not equal the other.
|
||||
*/
|
||||
Timestamp.prototype.notEquals = function(other) {
|
||||
return this.high_ !== other.high_ || this.low_ !== other.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is less than the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} whether this Timestamp is less than the other.
|
||||
*/
|
||||
Timestamp.prototype.lessThan = function(other) {
|
||||
return this.compare(other) < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is less than or equal to the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} whether this Timestamp is less than or equal to the other.
|
||||
*/
|
||||
Timestamp.prototype.lessThanOrEqual = function(other) {
|
||||
return this.compare(other) <= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is greater than the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} whether this Timestamp is greater than the other.
|
||||
*/
|
||||
Timestamp.prototype.greaterThan = function(other) {
|
||||
return this.compare(other) > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is greater than or equal to the other.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} whether this Timestamp is greater than or equal to the other.
|
||||
*/
|
||||
Timestamp.prototype.greaterThanOrEqual = function(other) {
|
||||
return this.compare(other) >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares this Timestamp with the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
|
||||
*/
|
||||
Timestamp.prototype.compare = function(other) {
|
||||
if (this.equals(other)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var thisNeg = this.isNegative();
|
||||
var otherNeg = other.isNegative();
|
||||
if (thisNeg && !otherNeg) {
|
||||
return -1;
|
||||
}
|
||||
if (!thisNeg && otherNeg) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// at this point, the signs are the same, so subtraction will not overflow
|
||||
if (this.subtract(other).isNegative()) {
|
||||
return -1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The negation of this value.
|
||||
*
|
||||
* @method
|
||||
* @return {Timestamp} the negation of this value.
|
||||
*/
|
||||
Timestamp.prototype.negate = function() {
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
return Timestamp.MIN_VALUE;
|
||||
} else {
|
||||
return this.not().add(Timestamp.ONE);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the sum of this and the given Timestamp.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to add to this one.
|
||||
* @return {Timestamp} the sum of this and the given Timestamp.
|
||||
*/
|
||||
Timestamp.prototype.add = function(other) {
|
||||
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xffff;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xffff;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xffff;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xffff;
|
||||
|
||||
var c48 = 0,
|
||||
c32 = 0,
|
||||
c16 = 0,
|
||||
c00 = 0;
|
||||
c00 += a00 + b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xffff;
|
||||
c16 += a16 + b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xffff;
|
||||
c32 += a32 + b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c48 += a48 + b48;
|
||||
c48 &= 0xffff;
|
||||
return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the difference of this and the given Timestamp.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to subtract from this.
|
||||
* @return {Timestamp} the difference of this and the given Timestamp.
|
||||
*/
|
||||
Timestamp.prototype.subtract = function(other) {
|
||||
return this.add(other.negate());
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the product of this and the given Timestamp.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp to multiply with this.
|
||||
* @return {Timestamp} the product of this and the other.
|
||||
*/
|
||||
Timestamp.prototype.multiply = function(other) {
|
||||
if (this.isZero()) {
|
||||
return Timestamp.ZERO;
|
||||
} else if (other.isZero()) {
|
||||
return Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
|
||||
} else if (other.equals(Timestamp.MIN_VALUE)) {
|
||||
return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().multiply(other.negate());
|
||||
} else {
|
||||
return this.negate()
|
||||
.multiply(other)
|
||||
.negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.multiply(other.negate()).negate();
|
||||
}
|
||||
|
||||
// If both Timestamps are small, use float multiplication
|
||||
if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) {
|
||||
return Timestamp.fromNumber(this.toNumber() * other.toNumber());
|
||||
}
|
||||
|
||||
// Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
// We can skip products that would overflow.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xffff;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xffff;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xffff;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xffff;
|
||||
|
||||
var c48 = 0,
|
||||
c32 = 0,
|
||||
c16 = 0,
|
||||
c00 = 0;
|
||||
c00 += a00 * b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xffff;
|
||||
c16 += a16 * b00;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xffff;
|
||||
c16 += a00 * b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xffff;
|
||||
c32 += a32 * b00;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c32 += a16 * b16;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c32 += a00 * b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xffff;
|
||||
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
|
||||
c48 &= 0xffff;
|
||||
return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp divided by the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp by which to divide.
|
||||
* @return {Timestamp} this Timestamp divided by the given one.
|
||||
*/
|
||||
Timestamp.prototype.div = function(other) {
|
||||
if (other.isZero()) {
|
||||
throw Error('division by zero');
|
||||
} else if (this.isZero()) {
|
||||
return Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) {
|
||||
return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
||||
} else if (other.equals(Timestamp.MIN_VALUE)) {
|
||||
return Timestamp.ONE;
|
||||
} else {
|
||||
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
var halfThis = this.shiftRight(1);
|
||||
var approx = halfThis.div(other).shiftLeft(1);
|
||||
if (approx.equals(Timestamp.ZERO)) {
|
||||
return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;
|
||||
} else {
|
||||
var rem = this.subtract(other.multiply(approx));
|
||||
var result = approx.add(rem.div(other));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (other.equals(Timestamp.MIN_VALUE)) {
|
||||
return Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().div(other.negate());
|
||||
} else {
|
||||
return this.negate()
|
||||
.div(other)
|
||||
.negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.div(other.negate()).negate();
|
||||
}
|
||||
|
||||
// Repeat the following until the remainder is less than other: find a
|
||||
// floating-point that approximates remainder / other *from below*, add this
|
||||
// into the result, and subtract it from the remainder. It is critical that
|
||||
// the approximate value is less than or equal to the real value so that the
|
||||
// remainder never becomes negative.
|
||||
var res = Timestamp.ZERO;
|
||||
rem = this;
|
||||
while (rem.greaterThanOrEqual(other)) {
|
||||
// Approximate the result of division. This may be a little greater or
|
||||
// smaller than the actual value.
|
||||
approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
|
||||
|
||||
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
// the smallest non-fractional digit, whichever is larger.
|
||||
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
|
||||
var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
|
||||
|
||||
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
// that if it is too large, the product overflows and is negative.
|
||||
var approxRes = Timestamp.fromNumber(approx);
|
||||
var approxRem = approxRes.multiply(other);
|
||||
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
|
||||
approx -= delta;
|
||||
approxRes = Timestamp.fromNumber(approx);
|
||||
approxRem = approxRes.multiply(other);
|
||||
}
|
||||
|
||||
// We know the answer can't be zero... and actually, zero would cause
|
||||
// infinite recursion since we would make no progress.
|
||||
if (approxRes.isZero()) {
|
||||
approxRes = Timestamp.ONE;
|
||||
}
|
||||
|
||||
res = res.add(approxRes);
|
||||
rem = rem.subtract(approxRem);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp modulo the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other Timestamp by which to mod.
|
||||
* @return {Timestamp} this Timestamp modulo the given one.
|
||||
*/
|
||||
Timestamp.prototype.modulo = function(other) {
|
||||
return this.subtract(this.div(other).multiply(other));
|
||||
};
|
||||
|
||||
/**
|
||||
* The bitwise-NOT of this value.
|
||||
*
|
||||
* @method
|
||||
* @return {Timestamp} the bitwise-NOT of this value.
|
||||
*/
|
||||
Timestamp.prototype.not = function() {
|
||||
return Timestamp.fromBits(~this.low_, ~this.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-AND of this Timestamp and the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other the Timestamp with which to AND.
|
||||
* @return {Timestamp} the bitwise-AND of this and the other.
|
||||
*/
|
||||
Timestamp.prototype.and = function(other) {
|
||||
return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-OR of this Timestamp and the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other the Timestamp with which to OR.
|
||||
* @return {Timestamp} the bitwise-OR of this and the other.
|
||||
*/
|
||||
Timestamp.prototype.or = function(other) {
|
||||
return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-XOR of this Timestamp and the given one.
|
||||
*
|
||||
* @method
|
||||
* @param {Timestamp} other the Timestamp with which to XOR.
|
||||
* @return {Timestamp} the bitwise-XOR of this and the other.
|
||||
*/
|
||||
Timestamp.prototype.xor = function(other) {
|
||||
return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp with bits shifted to the left by the given amount.
|
||||
*
|
||||
* @method
|
||||
* @param {number} numBits the number of bits by which to shift.
|
||||
* @return {Timestamp} this shifted to the left by the given amount.
|
||||
*/
|
||||
Timestamp.prototype.shiftLeft = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits === 0) {
|
||||
return this;
|
||||
} else {
|
||||
var low = this.low_;
|
||||
if (numBits < 32) {
|
||||
var high = this.high_;
|
||||
return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits)));
|
||||
} else {
|
||||
return Timestamp.fromBits(0, low << (numBits - 32));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp with bits shifted to the right by the given amount.
|
||||
*
|
||||
* @method
|
||||
* @param {number} numBits the number of bits by which to shift.
|
||||
* @return {Timestamp} this shifted to the right by the given amount.
|
||||
*/
|
||||
Timestamp.prototype.shiftRight = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits === 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits);
|
||||
} else {
|
||||
return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
|
||||
*
|
||||
* @method
|
||||
* @param {number} numBits the number of bits by which to shift.
|
||||
* @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.
|
||||
*/
|
||||
Timestamp.prototype.shiftRightUnsigned = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits === 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits);
|
||||
} else if (numBits === 32) {
|
||||
return Timestamp.fromBits(high, 0);
|
||||
} else {
|
||||
return Timestamp.fromBits(high >>> (numBits - 32), 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representing the given (32-bit) integer value.
|
||||
*
|
||||
* @method
|
||||
* @param {number} value the 32-bit integer in question.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
*/
|
||||
Timestamp.fromInt = function(value) {
|
||||
if (-128 <= value && value < 128) {
|
||||
var cachedObj = Timestamp.INT_CACHE_[value];
|
||||
if (cachedObj) {
|
||||
return cachedObj;
|
||||
}
|
||||
}
|
||||
|
||||
var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);
|
||||
if (-128 <= value && value < 128) {
|
||||
Timestamp.INT_CACHE_[value] = obj;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned.
|
||||
*
|
||||
* @method
|
||||
* @param {number} value the number in question.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
*/
|
||||
Timestamp.fromNumber = function(value) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return Timestamp.ZERO;
|
||||
} else if (value <= -Timestamp.TWO_PWR_63_DBL_) {
|
||||
return Timestamp.MIN_VALUE;
|
||||
} else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {
|
||||
return Timestamp.MAX_VALUE;
|
||||
} else if (value < 0) {
|
||||
return Timestamp.fromNumber(-value).negate();
|
||||
} else {
|
||||
return new Timestamp(
|
||||
(value % Timestamp.TWO_PWR_32_DBL_) | 0,
|
||||
(value / Timestamp.TWO_PWR_32_DBL_) | 0
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
|
||||
*
|
||||
* @method
|
||||
* @param {number} lowBits the low 32-bits.
|
||||
* @param {number} highBits the high 32-bits.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
*/
|
||||
Timestamp.fromBits = function(lowBits, highBits) {
|
||||
return new Timestamp(lowBits, highBits);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representation of the given string, written using the given radix.
|
||||
*
|
||||
* @method
|
||||
* @param {string} str the textual representation of the Timestamp.
|
||||
* @param {number} opt_radix the radix in which the text is written.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
*/
|
||||
Timestamp.fromString = function(str, opt_radix) {
|
||||
if (str.length === 0) {
|
||||
throw Error('number format error: empty string');
|
||||
}
|
||||
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (str.charAt(0) === '-') {
|
||||
return Timestamp.fromString(str.substring(1), radix).negate();
|
||||
} else if (str.indexOf('-') >= 0) {
|
||||
throw Error('number format error: interior "-" character: ' + str);
|
||||
}
|
||||
|
||||
// Do several (8) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8));
|
||||
|
||||
var result = Timestamp.ZERO;
|
||||
for (var i = 0; i < str.length; i += 8) {
|
||||
var size = Math.min(8, str.length - i);
|
||||
var value = parseInt(str.substring(i, i + size), radix);
|
||||
if (size < 8) {
|
||||
var power = Timestamp.fromNumber(Math.pow(radix, size));
|
||||
result = result.multiply(power).add(Timestamp.fromNumber(value));
|
||||
} else {
|
||||
result = result.multiply(radixToPower);
|
||||
result = result.add(Timestamp.fromNumber(value));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
// from* methods on which they depend.
|
||||
|
||||
/**
|
||||
* A cache of the Timestamp representations of small integer values.
|
||||
* @type {Object}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.INT_CACHE_ = {};
|
||||
|
||||
// NOTE: the compiler should inline these constant values below and then remove
|
||||
// these variables, so there should be no runtime penalty for these.
|
||||
|
||||
/**
|
||||
* Number used repeated below in calculations. This must appear before the
|
||||
* first call to any from* function below.
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_16_DBL_ = 1 << 16;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_24_DBL_ = 1 << 24;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.ZERO = Timestamp.fromInt(0);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.ONE = Timestamp.fromInt(1);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.NEG_ONE = Timestamp.fromInt(-1);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);
|
||||
|
||||
/**
|
||||
* @type {Timestamp}
|
||||
* @ignore
|
||||
*/
|
||||
Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
module.exports = Timestamp;
|
||||
module.exports.Timestamp = Timestamp;
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
{
|
||||
"_from": "bson@~1.1.1",
|
||||
"_id": "bson@1.1.1",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==",
|
||||
"_location": "/mongoose/bson",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "bson@~1.1.1",
|
||||
"name": "bson",
|
||||
"escapedName": "bson",
|
||||
"rawSpec": "~1.1.1",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "~1.1.1"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/mongoose",
|
||||
"/mongoose/mongodb-core"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz",
|
||||
"_shasum": "4330f5e99104c4e751e7351859e2d408279f2f13",
|
||||
"_spec": "bson@~1.1.1",
|
||||
"_where": "/home/erik/Documents/workspace_brackets/a1_BME_Project_Ohm/om/node_modules/mongoose",
|
||||
"author": {
|
||||
"name": "Christian Amor Kvalheim",
|
||||
"email": "christkv@gmail.com"
|
||||
},
|
||||
"browser": "lib/bson/bson.js",
|
||||
"bugs": {
|
||||
"url": "https://github.com/mongodb/js-bson/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"config": {
|
||||
"native": false
|
||||
},
|
||||
"contributors": [],
|
||||
"deprecated": false,
|
||||
"description": "A bson parser for node.js and the browser",
|
||||
"devDependencies": {
|
||||
"babel-core": "^6.14.0",
|
||||
"babel-loader": "^6.2.5",
|
||||
"babel-polyfill": "^6.13.0",
|
||||
"babel-preset-es2015": "^6.14.0",
|
||||
"babel-preset-stage-0": "^6.5.0",
|
||||
"babel-register": "^6.14.0",
|
||||
"benchmark": "1.0.0",
|
||||
"colors": "1.1.0",
|
||||
"conventional-changelog-cli": "^1.3.5",
|
||||
"nodeunit": "0.9.0",
|
||||
"webpack": "^1.13.2",
|
||||
"webpack-polyfills-plugin": "0.0.9"
|
||||
},
|
||||
"directories": {
|
||||
"lib": "./lib/bson"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6.19"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"index.js",
|
||||
"browser_build",
|
||||
"bower.json"
|
||||
],
|
||||
"homepage": "https://github.com/mongodb/js-bson#readme",
|
||||
"keywords": [
|
||||
"mongodb",
|
||||
"bson",
|
||||
"parser"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"main": "./index",
|
||||
"name": "bson",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/mongodb/js-bson.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "webpack --config ./webpack.dist.config.js",
|
||||
"changelog": "conventional-changelog -p angular -i HISTORY.md -s",
|
||||
"format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'",
|
||||
"lint": "eslint lib test",
|
||||
"test": "nodeunit ./test/node"
|
||||
},
|
||||
"version": "1.1.1"
|
||||
}
|
||||
-1168
File diff suppressed because it is too large
Load Diff
-201
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-228
@@ -1,228 +0,0 @@
|
||||
[](http://travis-ci.org/mongodb-js/mongodb-core)
|
||||
[](https://coveralls.io/github/mongodb-js/mongodb-core?branch=1.3)
|
||||
|
||||
# Description
|
||||
|
||||
The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication.
|
||||
|
||||
## MongoDB Node.JS Core Driver
|
||||
|
||||
| what | where |
|
||||
|---------------|------------------------------------------------|
|
||||
| documentation | http://mongodb.github.io/node-mongodb-native/ |
|
||||
| apidoc | http://mongodb.github.io/node-mongodb-native/ |
|
||||
| source | https://github.com/mongodb-js/mongodb-core |
|
||||
| mongodb | http://www.mongodb.org/ |
|
||||
|
||||
### Blogs of Engineers involved in the driver
|
||||
- Christian Kvalheim [@christkv](https://twitter.com/christkv) <http://christiankvalheim.com>
|
||||
|
||||
### Bugs / Feature Requests
|
||||
|
||||
Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a
|
||||
case in our issue management tool, JIRA:
|
||||
|
||||
- Create an account and login <https://jira.mongodb.org>.
|
||||
- Navigate to the NODE project <https://jira.mongodb.org/browse/NODE>.
|
||||
- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.
|
||||
|
||||
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the
|
||||
Core Server (i.e. SERVER) project are **public**.
|
||||
|
||||
### Questions and Bug Reports
|
||||
|
||||
* mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native
|
||||
* jira: http://jira.mongodb.org/
|
||||
|
||||
### Change Log
|
||||
|
||||
http://jira.mongodb.org/browse/NODE
|
||||
|
||||
# QuickStart
|
||||
|
||||
The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials.
|
||||
|
||||
## Create the package.json file
|
||||
|
||||
Let's create a directory where our application will live. In our case we will put this under our projects directory.
|
||||
|
||||
```
|
||||
mkdir myproject
|
||||
cd myproject
|
||||
```
|
||||
|
||||
Create a **package.json** using your favorite text editor and fill it in.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "myproject",
|
||||
"version": "1.0.0",
|
||||
"description": "My first project",
|
||||
"main": "index.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/christkv/myfirstproject.git"
|
||||
},
|
||||
"dependencies": {
|
||||
"mongodb-core": "~1.0"
|
||||
},
|
||||
"author": "Christian Kvalheim",
|
||||
"license": "Apache 2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/christkv/myfirstproject/issues"
|
||||
},
|
||||
"homepage": "https://github.com/christkv/myfirstproject"
|
||||
}
|
||||
```
|
||||
|
||||
Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies.
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory.
|
||||
|
||||
Booting up a MongoDB Server
|
||||
---------------------------
|
||||
Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**).
|
||||
|
||||
```
|
||||
mongod --dbpath=/data --port 27017
|
||||
```
|
||||
|
||||
You should see the **mongod** process start up and print some status information.
|
||||
|
||||
## Connecting to MongoDB
|
||||
|
||||
Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver.
|
||||
|
||||
First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection.
|
||||
|
||||
```js
|
||||
var Server = require('mongodb-core').Server
|
||||
, assert = require('assert');
|
||||
|
||||
// Set up server connection
|
||||
var server = new Server({
|
||||
host: 'localhost'
|
||||
, port: 27017
|
||||
, reconnect: true
|
||||
, reconnectInterval: 50
|
||||
});
|
||||
|
||||
// Add event listeners
|
||||
server.on('connect', function(_server) {
|
||||
console.log('connected');
|
||||
test.done();
|
||||
});
|
||||
|
||||
server.on('close', function() {
|
||||
console.log('closed');
|
||||
});
|
||||
|
||||
server.on('reconnect', function() {
|
||||
console.log('reconnect');
|
||||
});
|
||||
|
||||
// Start connection
|
||||
server.connect();
|
||||
```
|
||||
|
||||
To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations.
|
||||
|
||||
```js
|
||||
var Server = require('mongodb-core').Server
|
||||
, assert = require('assert');
|
||||
|
||||
// Set up server connection
|
||||
var server = new Server({
|
||||
host: 'localhost'
|
||||
, port: 27017
|
||||
, reconnect: true
|
||||
, reconnectInterval: 50
|
||||
});
|
||||
|
||||
// Add event listeners
|
||||
server.on('connect', function(_server) {
|
||||
console.log('connected');
|
||||
|
||||
// Execute the ismaster command
|
||||
_server.command('system.$cmd', {ismaster: true}, function(err, result) {
|
||||
|
||||
// Perform a document insert
|
||||
_server.insert('myproject.inserts1', [{a:1}, {a:2}], {
|
||||
writeConcern: {w:1}, ordered:true
|
||||
}, function(err, results) {
|
||||
assert.equal(null, err);
|
||||
assert.equal(2, results.result.n);
|
||||
|
||||
// Perform a document update
|
||||
_server.update('myproject.inserts1', [{
|
||||
q: {a: 1}, u: {'$set': {b:1}}
|
||||
}], {
|
||||
writeConcern: {w:1}, ordered:true
|
||||
}, function(err, results) {
|
||||
assert.equal(null, err);
|
||||
assert.equal(1, results.result.n);
|
||||
|
||||
// Remove a document
|
||||
_server.remove('myproject.inserts1', [{
|
||||
q: {a: 1}, limit: 1
|
||||
}], {
|
||||
writeConcern: {w:1}, ordered:true
|
||||
}, function(err, results) {
|
||||
assert.equal(null, err);
|
||||
assert.equal(1, results.result.n);
|
||||
|
||||
// Get a document
|
||||
var cursor = _server.cursor('integration_tests.inserts_example4', {
|
||||
find: 'integration_tests.example4'
|
||||
, query: {a:1}
|
||||
});
|
||||
|
||||
// Get the first document
|
||||
cursor.next(function(err, doc) {
|
||||
assert.equal(null, err);
|
||||
assert.equal(2, doc.a);
|
||||
|
||||
// Execute the ismaster command
|
||||
_server.command("system.$cmd"
|
||||
, {ismaster: true}, function(err, result) {
|
||||
assert.equal(null, err)
|
||||
_server.destroy();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test.done();
|
||||
});
|
||||
});
|
||||
|
||||
server.on('close', function() {
|
||||
console.log('closed');
|
||||
});
|
||||
|
||||
server.on('reconnect', function() {
|
||||
console.log('reconnect');
|
||||
});
|
||||
|
||||
// Start connection
|
||||
server.connect();
|
||||
```
|
||||
|
||||
The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands.
|
||||
|
||||
* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order.
|
||||
* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order.
|
||||
* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order.
|
||||
* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage.
|
||||
* `command`, Executes a command against MongoDB and returns the result.
|
||||
* `auth`, Authenticates the current topology using a supported authentication scheme.
|
||||
|
||||
The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction.
|
||||
|
||||
## Next steps
|
||||
|
||||
The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information.
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var BSON = require('bson');
|
||||
var require_optional = require('require_optional');
|
||||
const EJSON = require('./lib/utils').retrieveEJSON();
|
||||
|
||||
try {
|
||||
// Attempt to grab the native BSON parser
|
||||
var BSONNative = require_optional('bson-ext');
|
||||
// If we got the native parser, use it instead of the
|
||||
// Javascript one
|
||||
if (BSONNative) {
|
||||
BSON = BSONNative;
|
||||
}
|
||||
} catch (err) {} // eslint-disable-line
|
||||
|
||||
module.exports = {
|
||||
// Errors
|
||||
MongoError: require('./lib/error').MongoError,
|
||||
MongoNetworkError: require('./lib/error').MongoNetworkError,
|
||||
MongoParseError: require('./lib/error').MongoParseError,
|
||||
MongoTimeoutError: require('./lib/error').MongoTimeoutError,
|
||||
MongoWriteConcernError: require('./lib/error').MongoWriteConcernError,
|
||||
mongoErrorContextSymbol: require('./lib/error').mongoErrorContextSymbol,
|
||||
// Core
|
||||
Connection: require('./lib/connection/connection'),
|
||||
Server: require('./lib/topologies/server'),
|
||||
ReplSet: require('./lib/topologies/replset'),
|
||||
Mongos: require('./lib/topologies/mongos'),
|
||||
Logger: require('./lib/connection/logger'),
|
||||
Cursor: require('./lib/cursor'),
|
||||
ReadPreference: require('./lib/topologies/read_preference'),
|
||||
Sessions: require('./lib/sessions'),
|
||||
BSON: BSON,
|
||||
EJSON: EJSON,
|
||||
Topology: require('./lib/sdam/topology'),
|
||||
// Raw operations
|
||||
Query: require('./lib/connection/commands').Query,
|
||||
// Auth mechanisms
|
||||
MongoCredentials: require('./lib/auth/mongo_credentials').MongoCredentials,
|
||||
defaultAuthProviders: require('./lib/auth/defaultAuthProviders').defaultAuthProviders,
|
||||
MongoCR: require('./lib/auth/mongocr'),
|
||||
X509: require('./lib/auth/x509'),
|
||||
Plain: require('./lib/auth/plain'),
|
||||
GSSAPI: require('./lib/auth/gssapi'),
|
||||
ScramSHA1: require('./lib/auth/scram').ScramSHA1,
|
||||
ScramSHA256: require('./lib/auth/scram').ScramSHA256,
|
||||
// Utilities
|
||||
parseConnectionString: require('./lib/uri_parser')
|
||||
};
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const MongoError = require('../error').MongoError;
|
||||
|
||||
/**
|
||||
* Creates a new AuthProvider, which dictates how to authenticate for a given
|
||||
* mechanism.
|
||||
* @class
|
||||
*/
|
||||
class AuthProvider {
|
||||
constructor(bson) {
|
||||
this.bson = bson;
|
||||
this.authStore = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate
|
||||
* @method
|
||||
* @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection
|
||||
* @param {Connection[]} connections Connections to authenticate using this authenticator
|
||||
* @param {MongoCredentials} credentials Authentication credentials
|
||||
* @param {authResultCallback} callback The callback to return the result from the authentication
|
||||
*/
|
||||
auth(sendAuthCommand, connections, credentials, callback) {
|
||||
// Total connections
|
||||
let count = connections.length;
|
||||
|
||||
if (count === 0) {
|
||||
callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Valid connections
|
||||
let numberOfValidConnections = 0;
|
||||
let errorObject = null;
|
||||
|
||||
const execute = connection => {
|
||||
this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => {
|
||||
// Adjust count
|
||||
count = count - 1;
|
||||
|
||||
// If we have an error
|
||||
if (err) {
|
||||
errorObject = new MongoError(err);
|
||||
} else if (r && (r.$err || r.errmsg)) {
|
||||
errorObject = new MongoError(r);
|
||||
} else {
|
||||
numberOfValidConnections = numberOfValidConnections + 1;
|
||||
}
|
||||
|
||||
// Still authenticating against other connections.
|
||||
if (count !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// We have authenticated all connections
|
||||
if (numberOfValidConnections > 0) {
|
||||
// Store the auth details
|
||||
this.addCredentials(credentials);
|
||||
// Return correct authentication
|
||||
callback(null, true);
|
||||
} else {
|
||||
if (errorObject == null) {
|
||||
errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`);
|
||||
}
|
||||
callback(errorObject, false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const executeInNextTick = _connection => process.nextTick(() => execute(_connection));
|
||||
|
||||
// For each connection we need to authenticate
|
||||
while (connections.length > 0) {
|
||||
executeInNextTick(connections.shift());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implementation of a single connection authenticating. Is meant to be overridden.
|
||||
* Will error if called directly
|
||||
* @ignore
|
||||
*/
|
||||
_authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) {
|
||||
throw new Error('_authenticateSingleConnection must be overridden');
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds credentials to store only if it does not exist
|
||||
* @param {MongoCredentials} credentials credentials to add to store
|
||||
*/
|
||||
addCredentials(credentials) {
|
||||
const found = this.authStore.some(cred => cred.equals(credentials));
|
||||
|
||||
if (!found) {
|
||||
this.authStore.push(credentials);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re authenticate pool
|
||||
* @method
|
||||
* @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection
|
||||
* @param {Connection[]} connections Connections to authenticate using this authenticator
|
||||
* @param {authResultCallback} callback The callback to return the result from the authentication
|
||||
*/
|
||||
reauthenticate(sendAuthCommand, connections, callback) {
|
||||
const authStore = this.authStore.slice(0);
|
||||
let count = authStore.length;
|
||||
if (count === 0) {
|
||||
return callback(null, null);
|
||||
}
|
||||
|
||||
for (let i = 0; i < authStore.length; i++) {
|
||||
this.auth(sendAuthCommand, connections, authStore[i], function(err) {
|
||||
count = count - 1;
|
||||
if (count === 0) {
|
||||
callback(err, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove credentials that have been previously stored in the auth provider
|
||||
* @method
|
||||
* @param {string} source Name of database we are removing authStore details about
|
||||
* @return {object}
|
||||
*/
|
||||
logout(source) {
|
||||
this.authStore = this.authStore.filter(credentials => credentials.source !== source);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A function that writes authentication commands to a specific connection
|
||||
* @callback SendAuthCommand
|
||||
* @param {Connection} connection The connection to write to
|
||||
* @param {Command} command A command with a toBin method that can be written to a connection
|
||||
* @param {AuthWriteCallback} callback Callback called when command response is received
|
||||
*/
|
||||
|
||||
/**
|
||||
* A callback for a specific auth command
|
||||
* @callback AuthWriteCallback
|
||||
* @param {Error} err If command failed, an error from the server
|
||||
* @param {object} r The response from the server
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a result from an authentication strategy
|
||||
*
|
||||
* @callback authResultCallback
|
||||
* @param {error} error An error object. Set to null if no error present
|
||||
* @param {boolean} result The result of the authentication process
|
||||
*/
|
||||
|
||||
module.exports = { AuthProvider };
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const MongoCR = require('./mongocr');
|
||||
const X509 = require('./x509');
|
||||
const Plain = require('./plain');
|
||||
const GSSAPI = require('./gssapi');
|
||||
const SSPI = require('./sspi');
|
||||
const ScramSHA1 = require('./scram').ScramSHA1;
|
||||
const ScramSHA256 = require('./scram').ScramSHA256;
|
||||
|
||||
/**
|
||||
* Returns the default authentication providers.
|
||||
*
|
||||
* @param {BSON} bson Bson definition
|
||||
* @returns {Object} a mapping of auth names to auth types
|
||||
*/
|
||||
function defaultAuthProviders(bson) {
|
||||
return {
|
||||
mongocr: new MongoCR(bson),
|
||||
x509: new X509(bson),
|
||||
plain: new Plain(bson),
|
||||
gssapi: new GSSAPI(bson),
|
||||
sspi: new SSPI(bson),
|
||||
'scram-sha-1': new ScramSHA1(bson),
|
||||
'scram-sha-256': new ScramSHA256(bson)
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { defaultAuthProviders };
|
||||
-241
@@ -1,241 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
const retrieveKerberos = require('../utils').retrieveKerberos;
|
||||
let kerberos;
|
||||
|
||||
/**
|
||||
* Creates a new GSSAPI authentication mechanism
|
||||
* @class
|
||||
* @extends AuthProvider
|
||||
*/
|
||||
class GSSAPI extends AuthProvider {
|
||||
/**
|
||||
* Implementation of authentication for a single connection
|
||||
* @override
|
||||
*/
|
||||
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
|
||||
const source = credentials.source;
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const mechanismProperties = credentials.mechanismProperties;
|
||||
const gssapiServiceName =
|
||||
mechanismProperties['gssapiservicename'] ||
|
||||
mechanismProperties['gssapiServiceName'] ||
|
||||
'mongodb';
|
||||
|
||||
GSSAPIInitialize(
|
||||
this,
|
||||
kerberos.processes.MongoAuthProcess,
|
||||
source,
|
||||
username,
|
||||
password,
|
||||
source,
|
||||
gssapiServiceName,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
mechanismProperties,
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate
|
||||
* @override
|
||||
* @method
|
||||
*/
|
||||
auth(sendAuthCommand, connections, credentials, callback) {
|
||||
if (kerberos == null) {
|
||||
try {
|
||||
kerberos = retrieveKerberos();
|
||||
} catch (e) {
|
||||
return callback(e, null);
|
||||
}
|
||||
}
|
||||
|
||||
super.auth(sendAuthCommand, connections, credentials, callback);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Initialize step
|
||||
var GSSAPIInitialize = function(
|
||||
self,
|
||||
MongoAuthProcess,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
gssapiServiceName,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
options,
|
||||
callback
|
||||
) {
|
||||
// Create authenticator
|
||||
var mongo_auth_process = new MongoAuthProcess(
|
||||
connection.host,
|
||||
connection.port,
|
||||
gssapiServiceName,
|
||||
options
|
||||
);
|
||||
|
||||
// Perform initialization
|
||||
mongo_auth_process.init(username, password, function(err) {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
// Perform the first step
|
||||
mongo_auth_process.transition('', function(err, payload) {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
// Call the next db step
|
||||
MongoDBGSSAPIFirstStep(
|
||||
self,
|
||||
mongo_auth_process,
|
||||
payload,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
callback
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Perform first step against mongodb
|
||||
var MongoDBGSSAPIFirstStep = function(
|
||||
self,
|
||||
mongo_auth_process,
|
||||
payload,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
callback
|
||||
) {
|
||||
// Build the sasl start command
|
||||
var command = {
|
||||
saslStart: 1,
|
||||
mechanism: 'GSSAPI',
|
||||
payload: payload,
|
||||
autoAuthorize: 1
|
||||
};
|
||||
|
||||
// Write the commmand on the connection
|
||||
sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => {
|
||||
if (err) return callback(err, false);
|
||||
// Execute mongodb transition
|
||||
mongo_auth_process.transition(doc.payload, function(err, payload) {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
// MongoDB API Second Step
|
||||
MongoDBGSSAPISecondStep(
|
||||
self,
|
||||
mongo_auth_process,
|
||||
payload,
|
||||
doc,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
callback
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Perform first step against mongodb
|
||||
var MongoDBGSSAPISecondStep = function(
|
||||
self,
|
||||
mongo_auth_process,
|
||||
payload,
|
||||
doc,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
callback
|
||||
) {
|
||||
// Build Authentication command to send to MongoDB
|
||||
var command = {
|
||||
saslContinue: 1,
|
||||
conversationId: doc.conversationId,
|
||||
payload: payload
|
||||
};
|
||||
|
||||
// Execute the command
|
||||
// Write the commmand on the connection
|
||||
sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => {
|
||||
if (err) return callback(err, false);
|
||||
// Call next transition for kerberos
|
||||
mongo_auth_process.transition(doc.payload, function(err, payload) {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
// Call the last and third step
|
||||
MongoDBGSSAPIThirdStep(
|
||||
self,
|
||||
mongo_auth_process,
|
||||
payload,
|
||||
doc,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
callback
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
var MongoDBGSSAPIThirdStep = function(
|
||||
self,
|
||||
mongo_auth_process,
|
||||
payload,
|
||||
doc,
|
||||
db,
|
||||
username,
|
||||
password,
|
||||
authdb,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
callback
|
||||
) {
|
||||
// Build final command
|
||||
var command = {
|
||||
saslContinue: 1,
|
||||
conversationId: doc.conversationId,
|
||||
payload: payload
|
||||
};
|
||||
|
||||
// Execute the command
|
||||
sendAuthCommand(connection, '$external.$cmd', command, (err, r) => {
|
||||
if (err) return callback(err, false);
|
||||
mongo_auth_process.transition(null, function(err) {
|
||||
if (err) return callback(err, null);
|
||||
callback(null, r);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* This is a result from a authentication strategy
|
||||
*
|
||||
* @callback authResultCallback
|
||||
* @param {error} error An error object. Set to null if no error present
|
||||
* @param {boolean} result The result of the authentication process
|
||||
*/
|
||||
|
||||
module.exports = GSSAPI;
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// Resolves the default auth mechanism according to
|
||||
// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst
|
||||
function getDefaultAuthMechanism(ismaster) {
|
||||
if (ismaster) {
|
||||
// If ismaster contains saslSupportedMechs, use scram-sha-256
|
||||
// if it is available, else scram-sha-1
|
||||
if (Array.isArray(ismaster.saslSupportedMechs)) {
|
||||
return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0
|
||||
? 'scram-sha-256'
|
||||
: 'scram-sha-1';
|
||||
}
|
||||
|
||||
// Fallback to legacy selection method. If wire version >= 3, use scram-sha-1
|
||||
if (ismaster.maxWireVersion >= 3) {
|
||||
return 'scram-sha-1';
|
||||
}
|
||||
}
|
||||
|
||||
// Default for wireprotocol < 3
|
||||
return 'mongocr';
|
||||
}
|
||||
|
||||
/**
|
||||
* A representation of the credentials used by MongoDB
|
||||
* @class
|
||||
* @property {string} mechanism The method used to authenticate
|
||||
* @property {string} [username] The username used for authentication
|
||||
* @property {string} [password] The password used for authentication
|
||||
* @property {string} [source] The database that the user should authenticate against
|
||||
* @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms
|
||||
*/
|
||||
class MongoCredentials {
|
||||
/**
|
||||
* Creates a new MongoCredentials object
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.username] The username used for authentication
|
||||
* @param {string} [options.password] The password used for authentication
|
||||
* @param {string} [options.source] The database that the user should authenticate against
|
||||
* @param {string} [options.mechanism] The method used to authenticate
|
||||
* @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms
|
||||
*/
|
||||
constructor(options) {
|
||||
options = options || {};
|
||||
this.username = options.username;
|
||||
this.password = options.password;
|
||||
this.source = options.source || options.db;
|
||||
this.mechanism = options.mechanism || 'default';
|
||||
this.mechanismProperties = options.mechanismProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if two MongoCredentials objects are equivalent
|
||||
* @param {MongoCredentials} other another MongoCredentials object
|
||||
* @returns {boolean} true if the two objects are equal.
|
||||
*/
|
||||
equals(other) {
|
||||
return (
|
||||
this.mechanism === other.mechanism &&
|
||||
this.username === other.username &&
|
||||
this.password === other.password &&
|
||||
this.source === other.source
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the authentication mechanism is set to "default", resolves the authMechanism
|
||||
* based on the server version and server supported sasl mechanisms.
|
||||
*
|
||||
* @param {Object} [ismaster] An ismaster response from the server
|
||||
*/
|
||||
resolveAuthMechanism(ismaster) {
|
||||
// If the mechanism is not "default", then it does not need to be resolved
|
||||
if (this.mechanism.toLowerCase() === 'default') {
|
||||
this.mechanism = getDefaultAuthMechanism(ismaster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { MongoCredentials };
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
/**
|
||||
* Creates a new MongoCR authentication mechanism
|
||||
*
|
||||
* @extends AuthProvider
|
||||
*/
|
||||
class MongoCR extends AuthProvider {
|
||||
/**
|
||||
* Implementation of authentication for a single connection
|
||||
* @override
|
||||
*/
|
||||
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const source = credentials.source;
|
||||
|
||||
sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => {
|
||||
let nonce = null;
|
||||
let key = null;
|
||||
|
||||
// Get nonce
|
||||
if (err == null) {
|
||||
nonce = r.nonce;
|
||||
// Use node md5 generator
|
||||
let md5 = crypto.createHash('md5');
|
||||
// Generate keys used for authentication
|
||||
md5.update(username + ':mongo:' + password, 'utf8');
|
||||
const hash_password = md5.digest('hex');
|
||||
// Final key
|
||||
md5 = crypto.createHash('md5');
|
||||
md5.update(nonce + username + hash_password, 'utf8');
|
||||
key = md5.digest('hex');
|
||||
}
|
||||
|
||||
const authenticateCommand = {
|
||||
authenticate: 1,
|
||||
user: username,
|
||||
nonce,
|
||||
key
|
||||
};
|
||||
|
||||
sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = MongoCR;
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const retrieveBSON = require('../connection/utils').retrieveBSON;
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
// TODO: can we get the Binary type from this.bson instead?
|
||||
const BSON = retrieveBSON();
|
||||
const Binary = BSON.Binary;
|
||||
|
||||
/**
|
||||
* Creates a new Plain authentication mechanism
|
||||
*
|
||||
* @extends AuthProvider
|
||||
*/
|
||||
class Plain extends AuthProvider {
|
||||
/**
|
||||
* Implementation of authentication for a single connection
|
||||
* @override
|
||||
*/
|
||||
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const payload = new Binary(`\x00${username}\x00${password}`);
|
||||
const command = {
|
||||
saslStart: 1,
|
||||
mechanism: 'PLAIN',
|
||||
payload: payload,
|
||||
autoAuthorize: 1
|
||||
};
|
||||
|
||||
sendAuthCommand(connection, '$external.$cmd', command, callback);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Plain;
|
||||
-293
@@ -1,293 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
const retrieveBSON = require('../connection/utils').retrieveBSON;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
const BSON = retrieveBSON();
|
||||
const Binary = BSON.Binary;
|
||||
|
||||
let saslprep;
|
||||
try {
|
||||
saslprep = require('saslprep');
|
||||
} catch (e) {
|
||||
// don't do anything;
|
||||
}
|
||||
|
||||
var parsePayload = function(payload) {
|
||||
var dict = {};
|
||||
var parts = payload.split(',');
|
||||
|
||||
for (var i = 0; i < parts.length; i++) {
|
||||
var valueParts = parts[i].split('=');
|
||||
dict[valueParts[0]] = valueParts[1];
|
||||
}
|
||||
|
||||
return dict;
|
||||
};
|
||||
|
||||
var passwordDigest = function(username, password) {
|
||||
if (typeof username !== 'string') throw new MongoError('username must be a string');
|
||||
if (typeof password !== 'string') throw new MongoError('password must be a string');
|
||||
if (password.length === 0) throw new MongoError('password cannot be empty');
|
||||
// Use node md5 generator
|
||||
var md5 = crypto.createHash('md5');
|
||||
// Generate keys used for authentication
|
||||
md5.update(username + ':mongo:' + password, 'utf8');
|
||||
return md5.digest('hex');
|
||||
};
|
||||
|
||||
// XOR two buffers
|
||||
function xor(a, b) {
|
||||
if (!Buffer.isBuffer(a)) a = Buffer.from(a);
|
||||
if (!Buffer.isBuffer(b)) b = Buffer.from(b);
|
||||
const length = Math.max(a.length, b.length);
|
||||
const res = [];
|
||||
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
res.push(a[i] ^ b[i]);
|
||||
}
|
||||
|
||||
return Buffer.from(res).toString('base64');
|
||||
}
|
||||
|
||||
function H(method, text) {
|
||||
return crypto
|
||||
.createHash(method)
|
||||
.update(text)
|
||||
.digest();
|
||||
}
|
||||
|
||||
function HMAC(method, key, text) {
|
||||
return crypto
|
||||
.createHmac(method, key)
|
||||
.update(text)
|
||||
.digest();
|
||||
}
|
||||
|
||||
var _hiCache = {};
|
||||
var _hiCacheCount = 0;
|
||||
var _hiCachePurge = function() {
|
||||
_hiCache = {};
|
||||
_hiCacheCount = 0;
|
||||
};
|
||||
|
||||
const hiLengthMap = {
|
||||
sha256: 32,
|
||||
sha1: 20
|
||||
};
|
||||
|
||||
function HI(data, salt, iterations, cryptoMethod) {
|
||||
// omit the work if already generated
|
||||
const key = [data, salt.toString('base64'), iterations].join('_');
|
||||
if (_hiCache[key] !== undefined) {
|
||||
return _hiCache[key];
|
||||
}
|
||||
|
||||
// generate the salt
|
||||
const saltedData = crypto.pbkdf2Sync(
|
||||
data,
|
||||
salt,
|
||||
iterations,
|
||||
hiLengthMap[cryptoMethod],
|
||||
cryptoMethod
|
||||
);
|
||||
|
||||
// cache a copy to speed up the next lookup, but prevent unbounded cache growth
|
||||
if (_hiCacheCount >= 200) {
|
||||
_hiCachePurge();
|
||||
}
|
||||
|
||||
_hiCache[key] = saltedData;
|
||||
_hiCacheCount += 1;
|
||||
return saltedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ScramSHA authentication mechanism
|
||||
* @class
|
||||
* @extends AuthProvider
|
||||
*/
|
||||
class ScramSHA extends AuthProvider {
|
||||
constructor(bson, cryptoMethod) {
|
||||
super(bson);
|
||||
this.cryptoMethod = cryptoMethod || 'sha1';
|
||||
}
|
||||
|
||||
static _getError(err, r) {
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
if (r.$err || r.errmsg) {
|
||||
return new MongoError(r);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
_executeScram(sendAuthCommand, connection, credentials, nonce, callback) {
|
||||
let username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const db = credentials.source;
|
||||
|
||||
const cryptoMethod = this.cryptoMethod;
|
||||
let mechanism = 'SCRAM-SHA-1';
|
||||
let processedPassword;
|
||||
|
||||
if (cryptoMethod === 'sha256') {
|
||||
mechanism = 'SCRAM-SHA-256';
|
||||
|
||||
processedPassword = saslprep ? saslprep(password) : password;
|
||||
} else {
|
||||
try {
|
||||
processedPassword = passwordDigest(username, password);
|
||||
} catch (e) {
|
||||
return callback(e);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up the user
|
||||
username = username.replace('=', '=3D').replace(',', '=2C');
|
||||
|
||||
// NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.
|
||||
// Since the username is not sasl-prep-d, we need to do this here.
|
||||
const firstBare = Buffer.concat([
|
||||
Buffer.from('n=', 'utf8'),
|
||||
Buffer.from(username, 'utf8'),
|
||||
Buffer.from(',r=', 'utf8'),
|
||||
Buffer.from(nonce, 'utf8')
|
||||
]);
|
||||
|
||||
// Build command structure
|
||||
const saslStartCmd = {
|
||||
saslStart: 1,
|
||||
mechanism,
|
||||
payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])),
|
||||
autoAuthorize: 1
|
||||
};
|
||||
|
||||
// Write the commmand on the connection
|
||||
sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => {
|
||||
let tmpError = ScramSHA._getError(err, r);
|
||||
if (tmpError) {
|
||||
return callback(tmpError, null);
|
||||
}
|
||||
|
||||
const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload;
|
||||
const dict = parsePayload(payload.value());
|
||||
const iterations = parseInt(dict.i, 10);
|
||||
const salt = dict.s;
|
||||
const rnonce = dict.r;
|
||||
|
||||
// Set up start of proof
|
||||
const withoutProof = `c=biws,r=${rnonce}`;
|
||||
const saltedPassword = HI(
|
||||
processedPassword,
|
||||
Buffer.from(salt, 'base64'),
|
||||
iterations,
|
||||
cryptoMethod
|
||||
);
|
||||
|
||||
if (iterations && iterations < 4096) {
|
||||
const error = new MongoError(`Server returned an invalid iteration count ${iterations}`);
|
||||
return callback(error, false);
|
||||
}
|
||||
|
||||
const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key');
|
||||
const storedKey = H(cryptoMethod, clientKey);
|
||||
const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(',');
|
||||
|
||||
const clientSignature = HMAC(cryptoMethod, storedKey, authMessage);
|
||||
const clientProof = `p=${xor(clientKey, clientSignature)}`;
|
||||
const clientFinal = [withoutProof, clientProof].join(',');
|
||||
const saslContinueCmd = {
|
||||
saslContinue: 1,
|
||||
conversationId: r.conversationId,
|
||||
payload: new Binary(Buffer.from(clientFinal))
|
||||
};
|
||||
|
||||
sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => {
|
||||
if (!r || r.done !== false) {
|
||||
return callback(err, r);
|
||||
}
|
||||
|
||||
const retrySaslContinueCmd = {
|
||||
saslContinue: 1,
|
||||
conversationId: r.conversationId,
|
||||
payload: Buffer.alloc(0)
|
||||
};
|
||||
|
||||
sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Implementation of authentication for a single connection
|
||||
* @override
|
||||
*/
|
||||
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
|
||||
// Create a random nonce
|
||||
crypto.randomBytes(24, (err, buff) => {
|
||||
if (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
return this._executeScram(
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
credentials,
|
||||
buff.toString('base64'),
|
||||
callback
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate
|
||||
* @override
|
||||
* @method
|
||||
*/
|
||||
auth(sendAuthCommand, connections, credentials, callback) {
|
||||
this._checkSaslprep();
|
||||
super.auth(sendAuthCommand, connections, credentials, callback);
|
||||
}
|
||||
|
||||
_checkSaslprep() {
|
||||
const cryptoMethod = this.cryptoMethod;
|
||||
|
||||
if (cryptoMethod === 'sha256') {
|
||||
if (!saslprep) {
|
||||
console.warn('Warning: no saslprep library specified. Passwords will not be sanitized');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ScramSHA1 authentication mechanism
|
||||
* @class
|
||||
* @extends ScramSHA
|
||||
*/
|
||||
class ScramSHA1 extends ScramSHA {
|
||||
constructor(bson) {
|
||||
super(bson, 'sha1');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ScramSHA256 authentication mechanism
|
||||
* @class
|
||||
* @extends ScramSHA
|
||||
*/
|
||||
class ScramSHA256 extends ScramSHA {
|
||||
constructor(bson) {
|
||||
super(bson, 'sha256');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { ScramSHA1, ScramSHA256 };
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
const retrieveKerberos = require('../utils').retrieveKerberos;
|
||||
let kerberos;
|
||||
|
||||
/**
|
||||
* Creates a new SSPI authentication mechanism
|
||||
* @class
|
||||
* @extends AuthProvider
|
||||
*/
|
||||
class SSPI extends AuthProvider {
|
||||
/**
|
||||
* Implementation of authentication for a single connection
|
||||
* @override
|
||||
*/
|
||||
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
|
||||
// TODO: Destructure this
|
||||
const username = credentials.username;
|
||||
const password = credentials.password;
|
||||
const mechanismProperties = credentials.mechanismProperties;
|
||||
const gssapiServiceName =
|
||||
mechanismProperties['gssapiservicename'] ||
|
||||
mechanismProperties['gssapiServiceName'] ||
|
||||
'mongodb';
|
||||
|
||||
SSIPAuthenticate(
|
||||
this,
|
||||
kerberos.processes.MongoAuthProcess,
|
||||
username,
|
||||
password,
|
||||
gssapiServiceName,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
mechanismProperties,
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate
|
||||
* @override
|
||||
* @method
|
||||
*/
|
||||
auth(sendAuthCommand, connections, credentials, callback) {
|
||||
if (kerberos == null) {
|
||||
try {
|
||||
kerberos = retrieveKerberos();
|
||||
} catch (e) {
|
||||
return callback(e, null);
|
||||
}
|
||||
}
|
||||
|
||||
super.auth(sendAuthCommand, connections, credentials, callback);
|
||||
}
|
||||
}
|
||||
|
||||
function SSIPAuthenticate(
|
||||
self,
|
||||
MongoAuthProcess,
|
||||
username,
|
||||
password,
|
||||
gssapiServiceName,
|
||||
sendAuthCommand,
|
||||
connection,
|
||||
options,
|
||||
callback
|
||||
) {
|
||||
const authProcess = new MongoAuthProcess(
|
||||
connection.host,
|
||||
connection.port,
|
||||
gssapiServiceName,
|
||||
options
|
||||
);
|
||||
|
||||
function authCommand(command, authCb) {
|
||||
sendAuthCommand(connection, '$external.$cmd', command, authCb);
|
||||
}
|
||||
|
||||
authProcess.init(username, password, err => {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
authProcess.transition('', (err, payload) => {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
const command = {
|
||||
saslStart: 1,
|
||||
mechanism: 'GSSAPI',
|
||||
payload,
|
||||
autoAuthorize: 1
|
||||
};
|
||||
|
||||
authCommand(command, (err, doc) => {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
authProcess.transition(doc.payload, (err, payload) => {
|
||||
if (err) return callback(err, false);
|
||||
const command = {
|
||||
saslContinue: 1,
|
||||
conversationId: doc.conversationId,
|
||||
payload
|
||||
};
|
||||
|
||||
authCommand(command, (err, doc) => {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
authProcess.transition(doc.payload, (err, payload) => {
|
||||
if (err) return callback(err, false);
|
||||
const command = {
|
||||
saslContinue: 1,
|
||||
conversationId: doc.conversationId,
|
||||
payload
|
||||
};
|
||||
|
||||
authCommand(command, (err, response) => {
|
||||
if (err) return callback(err, false);
|
||||
|
||||
authProcess.transition(null, err => {
|
||||
if (err) return callback(err, null);
|
||||
callback(null, response);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = SSPI;
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const AuthProvider = require('./auth_provider').AuthProvider;
|
||||
|
||||
/**
|
||||
* Creates a new X509 authentication mechanism
|
||||
* @class
|
||||
* @extends AuthProvider
|
||||
*/
|
||||
class X509 extends AuthProvider {
|
||||
/**
|
||||
* Implementation of authentication for a single connection
|
||||
* @override
|
||||
*/
|
||||
_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
|
||||
const username = credentials.username;
|
||||
const command = { authenticate: 1, mechanism: 'MONGODB-X509' };
|
||||
if (username) {
|
||||
command.user = username;
|
||||
}
|
||||
|
||||
sendAuthCommand(connection, '$external.$cmd', command, callback);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = X509;
|
||||
-236
@@ -1,236 +0,0 @@
|
||||
'use strict';
|
||||
const Msg = require('../connection/msg').Msg;
|
||||
const KillCursor = require('../connection/commands').KillCursor;
|
||||
const GetMore = require('../connection/commands').GetMore;
|
||||
const calculateDurationInMs = require('../utils').calculateDurationInMs;
|
||||
|
||||
/** Commands that we want to redact because of the sensitive nature of their contents */
|
||||
const SENSITIVE_COMMANDS = new Set([
|
||||
'authenticate',
|
||||
'saslStart',
|
||||
'saslContinue',
|
||||
'getnonce',
|
||||
'createUser',
|
||||
'updateUser',
|
||||
'copydbgetnonce',
|
||||
'copydbsaslstart',
|
||||
'copydb'
|
||||
]);
|
||||
|
||||
// helper methods
|
||||
const extractCommandName = commandDoc => Object.keys(commandDoc)[0];
|
||||
const namespace = command => command.ns;
|
||||
const databaseName = command => command.ns.split('.')[0];
|
||||
const collectionName = command => command.ns.split('.')[1];
|
||||
const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`;
|
||||
const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result);
|
||||
|
||||
const LEGACY_FIND_QUERY_MAP = {
|
||||
$query: 'filter',
|
||||
$orderby: 'sort',
|
||||
$hint: 'hint',
|
||||
$comment: 'comment',
|
||||
$maxScan: 'maxScan',
|
||||
$max: 'max',
|
||||
$min: 'min',
|
||||
$returnKey: 'returnKey',
|
||||
$showDiskLoc: 'showRecordId',
|
||||
$maxTimeMS: 'maxTimeMS',
|
||||
$snapshot: 'snapshot'
|
||||
};
|
||||
|
||||
const LEGACY_FIND_OPTIONS_MAP = {
|
||||
numberToSkip: 'skip',
|
||||
numberToReturn: 'batchSize',
|
||||
returnFieldsSelector: 'projection'
|
||||
};
|
||||
|
||||
const OP_QUERY_KEYS = [
|
||||
'tailable',
|
||||
'oplogReplay',
|
||||
'noCursorTimeout',
|
||||
'awaitData',
|
||||
'partial',
|
||||
'exhaust'
|
||||
];
|
||||
|
||||
/**
|
||||
* Extract the actual command from the query, possibly upconverting if it's a legacy
|
||||
* format
|
||||
*
|
||||
* @param {Object} command the command
|
||||
*/
|
||||
const extractCommand = command => {
|
||||
if (command instanceof GetMore) {
|
||||
return {
|
||||
getMore: command.cursorId,
|
||||
collection: collectionName(command),
|
||||
batchSize: command.numberToReturn
|
||||
};
|
||||
}
|
||||
|
||||
if (command instanceof KillCursor) {
|
||||
return {
|
||||
killCursors: collectionName(command),
|
||||
cursors: command.cursorIds
|
||||
};
|
||||
}
|
||||
|
||||
if (command instanceof Msg) {
|
||||
return command.command;
|
||||
}
|
||||
|
||||
if (command.query && command.query.$query) {
|
||||
let result;
|
||||
if (command.ns === 'admin.$cmd') {
|
||||
// upconvert legacy command
|
||||
result = Object.assign({}, command.query.$query);
|
||||
} else {
|
||||
// upconvert legacy find command
|
||||
result = { find: collectionName(command) };
|
||||
Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => {
|
||||
if (typeof command.query[key] !== 'undefined')
|
||||
result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key];
|
||||
});
|
||||
}
|
||||
|
||||
Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => {
|
||||
if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key];
|
||||
});
|
||||
|
||||
OP_QUERY_KEYS.forEach(key => {
|
||||
if (command[key]) result[key] = command[key];
|
||||
});
|
||||
|
||||
if (typeof command.pre32Limit !== 'undefined') {
|
||||
result.limit = command.pre32Limit;
|
||||
}
|
||||
|
||||
if (command.query.$explain) {
|
||||
return { explain: result };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return command.query ? command.query : command;
|
||||
};
|
||||
|
||||
const extractReply = (command, reply) => {
|
||||
if (command instanceof GetMore) {
|
||||
return {
|
||||
ok: 1,
|
||||
cursor: {
|
||||
id: reply.message.cursorId,
|
||||
ns: namespace(command),
|
||||
nextBatch: reply.message.documents
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (command instanceof KillCursor) {
|
||||
return {
|
||||
ok: 1,
|
||||
cursorsUnknown: command.cursorIds
|
||||
};
|
||||
}
|
||||
|
||||
// is this a legacy find command?
|
||||
if (command.query && typeof command.query.$query !== 'undefined') {
|
||||
return {
|
||||
ok: 1,
|
||||
cursor: {
|
||||
id: reply.message.cursorId,
|
||||
ns: namespace(command),
|
||||
firstBatch: reply.message.documents
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// in the event of a `noResponse` command, just return
|
||||
if (reply === null) return reply;
|
||||
|
||||
return reply.result;
|
||||
};
|
||||
|
||||
/** An event indicating the start of a given command */
|
||||
class CommandStartedEvent {
|
||||
/**
|
||||
* Create a started event
|
||||
*
|
||||
* @param {Pool} pool the pool that originated the command
|
||||
* @param {Object} command the command
|
||||
*/
|
||||
constructor(pool, command) {
|
||||
const cmd = extractCommand(command);
|
||||
const commandName = extractCommandName(cmd);
|
||||
|
||||
// NOTE: remove in major revision, this is not spec behavior
|
||||
if (SENSITIVE_COMMANDS.has(commandName)) {
|
||||
this.commandObj = {};
|
||||
this.commandObj[commandName] = true;
|
||||
}
|
||||
|
||||
Object.assign(this, {
|
||||
command: cmd,
|
||||
databaseName: databaseName(command),
|
||||
commandName,
|
||||
requestId: command.requestId,
|
||||
connectionId: generateConnectionId(pool)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** An event indicating the success of a given command */
|
||||
class CommandSucceededEvent {
|
||||
/**
|
||||
* Create a succeeded event
|
||||
*
|
||||
* @param {Pool} pool the pool that originated the command
|
||||
* @param {Object} command the command
|
||||
* @param {Object} reply the reply for this command from the server
|
||||
* @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
|
||||
*/
|
||||
constructor(pool, command, reply, started) {
|
||||
const cmd = extractCommand(command);
|
||||
const commandName = extractCommandName(cmd);
|
||||
|
||||
Object.assign(this, {
|
||||
duration: calculateDurationInMs(started),
|
||||
commandName,
|
||||
reply: maybeRedact(commandName, extractReply(command, reply)),
|
||||
requestId: command.requestId,
|
||||
connectionId: generateConnectionId(pool)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** An event indicating the failure of a given command */
|
||||
class CommandFailedEvent {
|
||||
/**
|
||||
* Create a failure event
|
||||
*
|
||||
* @param {Pool} pool the pool that originated the command
|
||||
* @param {Object} command the command
|
||||
* @param {MongoError|Object} error the generated error or a server error response
|
||||
* @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
|
||||
*/
|
||||
constructor(pool, command, error, started) {
|
||||
const cmd = extractCommand(command);
|
||||
const commandName = extractCommandName(cmd);
|
||||
|
||||
Object.assign(this, {
|
||||
duration: calculateDurationInMs(started),
|
||||
commandName,
|
||||
failure: maybeRedact(commandName, error),
|
||||
requestId: command.requestId,
|
||||
connectionId: generateConnectionId(pool)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CommandStartedEvent,
|
||||
CommandSucceededEvent,
|
||||
CommandFailedEvent
|
||||
};
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Creates a new CommandResult instance
|
||||
* @class
|
||||
* @param {object} result CommandResult object
|
||||
* @param {Connection} connection A connection instance associated with this result
|
||||
* @return {CommandResult} A cursor instance
|
||||
*/
|
||||
var CommandResult = function(result, connection, message) {
|
||||
this.result = result;
|
||||
this.connection = connection;
|
||||
this.message = message;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert CommandResult to JSON
|
||||
* @method
|
||||
* @return {object}
|
||||
*/
|
||||
CommandResult.prototype.toJSON = function() {
|
||||
let result = Object.assign({}, this, this.result);
|
||||
delete result.message;
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert CommandResult to String representation
|
||||
* @method
|
||||
* @return {string}
|
||||
*/
|
||||
CommandResult.prototype.toString = function() {
|
||||
return JSON.stringify(this.toJSON());
|
||||
};
|
||||
|
||||
module.exports = CommandResult;
|
||||
-507
@@ -1,507 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var retrieveBSON = require('./utils').retrieveBSON;
|
||||
var BSON = retrieveBSON();
|
||||
var Long = BSON.Long;
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
// Incrementing request id
|
||||
var _requestId = 0;
|
||||
|
||||
// Wire command operation ids
|
||||
var opcodes = require('../wireprotocol/shared').opcodes;
|
||||
|
||||
// Query flags
|
||||
var OPTS_TAILABLE_CURSOR = 2;
|
||||
var OPTS_SLAVE = 4;
|
||||
var OPTS_OPLOG_REPLAY = 8;
|
||||
var OPTS_NO_CURSOR_TIMEOUT = 16;
|
||||
var OPTS_AWAIT_DATA = 32;
|
||||
var OPTS_EXHAUST = 64;
|
||||
var OPTS_PARTIAL = 128;
|
||||
|
||||
// Response flags
|
||||
var CURSOR_NOT_FOUND = 1;
|
||||
var QUERY_FAILURE = 2;
|
||||
var SHARD_CONFIG_STALE = 4;
|
||||
var AWAIT_CAPABLE = 8;
|
||||
|
||||
/**************************************************************
|
||||
* QUERY
|
||||
**************************************************************/
|
||||
var Query = function(bson, ns, query, options) {
|
||||
var self = this;
|
||||
// Basic options needed to be passed in
|
||||
if (ns == null) throw new Error('ns must be specified for query');
|
||||
if (query == null) throw new Error('query must be specified for query');
|
||||
|
||||
// Validate that we are not passing 0x00 in the collection name
|
||||
if (ns.indexOf('\x00') !== -1) {
|
||||
throw new Error('namespace cannot contain a null character');
|
||||
}
|
||||
|
||||
// Basic options
|
||||
this.bson = bson;
|
||||
this.ns = ns;
|
||||
this.query = query;
|
||||
|
||||
// Additional options
|
||||
this.numberToSkip = options.numberToSkip || 0;
|
||||
this.numberToReturn = options.numberToReturn || 0;
|
||||
this.returnFieldSelector = options.returnFieldSelector || null;
|
||||
this.requestId = Query.getRequestId();
|
||||
|
||||
// special case for pre-3.2 find commands, delete ASAP
|
||||
this.pre32Limit = options.pre32Limit;
|
||||
|
||||
// Serialization option
|
||||
this.serializeFunctions =
|
||||
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
|
||||
this.ignoreUndefined =
|
||||
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;
|
||||
this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
|
||||
this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true;
|
||||
this.batchSize = self.numberToReturn;
|
||||
|
||||
// Flags
|
||||
this.tailable = false;
|
||||
this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false;
|
||||
this.oplogReplay = false;
|
||||
this.noCursorTimeout = false;
|
||||
this.awaitData = false;
|
||||
this.exhaust = false;
|
||||
this.partial = false;
|
||||
};
|
||||
|
||||
//
|
||||
// Assign a new request Id
|
||||
Query.prototype.incRequestId = function() {
|
||||
this.requestId = _requestId++;
|
||||
};
|
||||
|
||||
//
|
||||
// Assign a new request Id
|
||||
Query.nextRequestId = function() {
|
||||
return _requestId + 1;
|
||||
};
|
||||
|
||||
//
|
||||
// Uses a single allocated buffer for the process, avoiding multiple memory allocations
|
||||
Query.prototype.toBin = function() {
|
||||
var self = this;
|
||||
var buffers = [];
|
||||
var projection = null;
|
||||
|
||||
// Set up the flags
|
||||
var flags = 0;
|
||||
if (this.tailable) {
|
||||
flags |= OPTS_TAILABLE_CURSOR;
|
||||
}
|
||||
|
||||
if (this.slaveOk) {
|
||||
flags |= OPTS_SLAVE;
|
||||
}
|
||||
|
||||
if (this.oplogReplay) {
|
||||
flags |= OPTS_OPLOG_REPLAY;
|
||||
}
|
||||
|
||||
if (this.noCursorTimeout) {
|
||||
flags |= OPTS_NO_CURSOR_TIMEOUT;
|
||||
}
|
||||
|
||||
if (this.awaitData) {
|
||||
flags |= OPTS_AWAIT_DATA;
|
||||
}
|
||||
|
||||
if (this.exhaust) {
|
||||
flags |= OPTS_EXHAUST;
|
||||
}
|
||||
|
||||
if (this.partial) {
|
||||
flags |= OPTS_PARTIAL;
|
||||
}
|
||||
|
||||
// If batchSize is different to self.numberToReturn
|
||||
if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize;
|
||||
|
||||
// Allocate write protocol header buffer
|
||||
var header = Buffer.alloc(
|
||||
4 * 4 + // Header
|
||||
4 + // Flags
|
||||
Buffer.byteLength(self.ns) +
|
||||
1 + // namespace
|
||||
4 + // numberToSkip
|
||||
4 // numberToReturn
|
||||
);
|
||||
|
||||
// Add header to buffers
|
||||
buffers.push(header);
|
||||
|
||||
// Serialize the query
|
||||
var query = self.bson.serialize(this.query, {
|
||||
checkKeys: this.checkKeys,
|
||||
serializeFunctions: this.serializeFunctions,
|
||||
ignoreUndefined: this.ignoreUndefined
|
||||
});
|
||||
|
||||
// Add query document
|
||||
buffers.push(query);
|
||||
|
||||
if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) {
|
||||
// Serialize the projection document
|
||||
projection = self.bson.serialize(this.returnFieldSelector, {
|
||||
checkKeys: this.checkKeys,
|
||||
serializeFunctions: this.serializeFunctions,
|
||||
ignoreUndefined: this.ignoreUndefined
|
||||
});
|
||||
// Add projection document
|
||||
buffers.push(projection);
|
||||
}
|
||||
|
||||
// Total message size
|
||||
var totalLength = header.length + query.length + (projection ? projection.length : 0);
|
||||
|
||||
// Set up the index
|
||||
var index = 4;
|
||||
|
||||
// Write total document length
|
||||
header[3] = (totalLength >> 24) & 0xff;
|
||||
header[2] = (totalLength >> 16) & 0xff;
|
||||
header[1] = (totalLength >> 8) & 0xff;
|
||||
header[0] = totalLength & 0xff;
|
||||
|
||||
// Write header information requestId
|
||||
header[index + 3] = (this.requestId >> 24) & 0xff;
|
||||
header[index + 2] = (this.requestId >> 16) & 0xff;
|
||||
header[index + 1] = (this.requestId >> 8) & 0xff;
|
||||
header[index] = this.requestId & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information responseTo
|
||||
header[index + 3] = (0 >> 24) & 0xff;
|
||||
header[index + 2] = (0 >> 16) & 0xff;
|
||||
header[index + 1] = (0 >> 8) & 0xff;
|
||||
header[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information OP_QUERY
|
||||
header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff;
|
||||
header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff;
|
||||
header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff;
|
||||
header[index] = opcodes.OP_QUERY & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information flags
|
||||
header[index + 3] = (flags >> 24) & 0xff;
|
||||
header[index + 2] = (flags >> 16) & 0xff;
|
||||
header[index + 1] = (flags >> 8) & 0xff;
|
||||
header[index] = flags & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write collection name
|
||||
index = index + header.write(this.ns, index, 'utf8') + 1;
|
||||
header[index - 1] = 0;
|
||||
|
||||
// Write header information flags numberToSkip
|
||||
header[index + 3] = (this.numberToSkip >> 24) & 0xff;
|
||||
header[index + 2] = (this.numberToSkip >> 16) & 0xff;
|
||||
header[index + 1] = (this.numberToSkip >> 8) & 0xff;
|
||||
header[index] = this.numberToSkip & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write header information flags numberToReturn
|
||||
header[index + 3] = (this.numberToReturn >> 24) & 0xff;
|
||||
header[index + 2] = (this.numberToReturn >> 16) & 0xff;
|
||||
header[index + 1] = (this.numberToReturn >> 8) & 0xff;
|
||||
header[index] = this.numberToReturn & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Return the buffers
|
||||
return buffers;
|
||||
};
|
||||
|
||||
Query.getRequestId = function() {
|
||||
return ++_requestId;
|
||||
};
|
||||
|
||||
/**************************************************************
|
||||
* GETMORE
|
||||
**************************************************************/
|
||||
var GetMore = function(bson, ns, cursorId, opts) {
|
||||
opts = opts || {};
|
||||
this.numberToReturn = opts.numberToReturn || 0;
|
||||
this.requestId = _requestId++;
|
||||
this.bson = bson;
|
||||
this.ns = ns;
|
||||
this.cursorId = cursorId;
|
||||
};
|
||||
|
||||
//
|
||||
// Uses a single allocated buffer for the process, avoiding multiple memory allocations
|
||||
GetMore.prototype.toBin = function() {
|
||||
var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4;
|
||||
// Create command buffer
|
||||
var index = 0;
|
||||
// Allocate buffer
|
||||
var _buffer = Buffer.alloc(length);
|
||||
|
||||
// Write header information
|
||||
// index = write32bit(index, _buffer, length);
|
||||
_buffer[index + 3] = (length >> 24) & 0xff;
|
||||
_buffer[index + 2] = (length >> 16) & 0xff;
|
||||
_buffer[index + 1] = (length >> 8) & 0xff;
|
||||
_buffer[index] = length & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, requestId);
|
||||
_buffer[index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_buffer[index] = this.requestId & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, OP_GETMORE);
|
||||
_buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff;
|
||||
_buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff;
|
||||
_buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff;
|
||||
_buffer[index] = opcodes.OP_GETMORE & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write collection name
|
||||
index = index + _buffer.write(this.ns, index, 'utf8') + 1;
|
||||
_buffer[index - 1] = 0;
|
||||
|
||||
// Write batch size
|
||||
// index = write32bit(index, _buffer, numberToReturn);
|
||||
_buffer[index + 3] = (this.numberToReturn >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.numberToReturn >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.numberToReturn >> 8) & 0xff;
|
||||
_buffer[index] = this.numberToReturn & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write cursor id
|
||||
// index = write32bit(index, _buffer, cursorId.getLowBits());
|
||||
_buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorId.getLowBits() & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, cursorId.getHighBits());
|
||||
_buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorId.getHighBits() & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Return buffer
|
||||
return _buffer;
|
||||
};
|
||||
|
||||
/**************************************************************
|
||||
* KILLCURSOR
|
||||
**************************************************************/
|
||||
var KillCursor = function(bson, ns, cursorIds) {
|
||||
this.ns = ns;
|
||||
this.requestId = _requestId++;
|
||||
this.cursorIds = cursorIds;
|
||||
};
|
||||
|
||||
//
|
||||
// Uses a single allocated buffer for the process, avoiding multiple memory allocations
|
||||
KillCursor.prototype.toBin = function() {
|
||||
var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8;
|
||||
|
||||
// Create command buffer
|
||||
var index = 0;
|
||||
var _buffer = Buffer.alloc(length);
|
||||
|
||||
// Write header information
|
||||
// index = write32bit(index, _buffer, length);
|
||||
_buffer[index + 3] = (length >> 24) & 0xff;
|
||||
_buffer[index + 2] = (length >> 16) & 0xff;
|
||||
_buffer[index + 1] = (length >> 8) & 0xff;
|
||||
_buffer[index] = length & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, requestId);
|
||||
_buffer[index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_buffer[index] = this.requestId & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, OP_KILL_CURSORS);
|
||||
_buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff;
|
||||
_buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff;
|
||||
_buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff;
|
||||
_buffer[index] = opcodes.OP_KILL_CURSORS & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, 0);
|
||||
_buffer[index + 3] = (0 >> 24) & 0xff;
|
||||
_buffer[index + 2] = (0 >> 16) & 0xff;
|
||||
_buffer[index + 1] = (0 >> 8) & 0xff;
|
||||
_buffer[index] = 0 & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write batch size
|
||||
// index = write32bit(index, _buffer, this.cursorIds.length);
|
||||
_buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorIds.length & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// Write all the cursor ids into the array
|
||||
for (var i = 0; i < this.cursorIds.length; i++) {
|
||||
// Write cursor id
|
||||
// index = write32bit(index, _buffer, cursorIds[i].getLowBits());
|
||||
_buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorIds[i].getLowBits() & 0xff;
|
||||
index = index + 4;
|
||||
|
||||
// index = write32bit(index, _buffer, cursorIds[i].getHighBits());
|
||||
_buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff;
|
||||
_buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff;
|
||||
_buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff;
|
||||
_buffer[index] = this.cursorIds[i].getHighBits() & 0xff;
|
||||
index = index + 4;
|
||||
}
|
||||
|
||||
// Return buffer
|
||||
return _buffer;
|
||||
};
|
||||
|
||||
var Response = function(bson, message, msgHeader, msgBody, opts) {
|
||||
opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false };
|
||||
this.parsed = false;
|
||||
this.raw = message;
|
||||
this.data = msgBody;
|
||||
this.bson = bson;
|
||||
this.opts = opts;
|
||||
|
||||
// Read the message header
|
||||
this.length = msgHeader.length;
|
||||
this.requestId = msgHeader.requestId;
|
||||
this.responseTo = msgHeader.responseTo;
|
||||
this.opCode = msgHeader.opCode;
|
||||
this.fromCompressed = msgHeader.fromCompressed;
|
||||
|
||||
// Read the message body
|
||||
this.responseFlags = msgBody.readInt32LE(0);
|
||||
this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8));
|
||||
this.startingFrom = msgBody.readInt32LE(12);
|
||||
this.numberReturned = msgBody.readInt32LE(16);
|
||||
|
||||
// Preallocate document array
|
||||
this.documents = new Array(this.numberReturned);
|
||||
|
||||
// Flag values
|
||||
this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0;
|
||||
this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0;
|
||||
this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0;
|
||||
this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0;
|
||||
this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true;
|
||||
this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true;
|
||||
this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false;
|
||||
};
|
||||
|
||||
Response.prototype.isParsed = function() {
|
||||
return this.parsed;
|
||||
};
|
||||
|
||||
Response.prototype.parse = function(options) {
|
||||
// Don't parse again if not needed
|
||||
if (this.parsed) return;
|
||||
options = options || {};
|
||||
|
||||
// Allow the return of raw documents instead of parsing
|
||||
var raw = options.raw || false;
|
||||
var documentsReturnedIn = options.documentsReturnedIn || null;
|
||||
var promoteLongs =
|
||||
typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs;
|
||||
var promoteValues =
|
||||
typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues;
|
||||
var promoteBuffers =
|
||||
typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers;
|
||||
var bsonSize, _options;
|
||||
|
||||
// Set up the options
|
||||
_options = {
|
||||
promoteLongs: promoteLongs,
|
||||
promoteValues: promoteValues,
|
||||
promoteBuffers: promoteBuffers
|
||||
};
|
||||
|
||||
// Position within OP_REPLY at which documents start
|
||||
// (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply)
|
||||
this.index = 20;
|
||||
|
||||
//
|
||||
// Parse Body
|
||||
//
|
||||
for (var i = 0; i < this.numberReturned; i++) {
|
||||
bsonSize =
|
||||
this.data[this.index] |
|
||||
(this.data[this.index + 1] << 8) |
|
||||
(this.data[this.index + 2] << 16) |
|
||||
(this.data[this.index + 3] << 24);
|
||||
|
||||
// If we have raw results specified slice the return document
|
||||
if (raw) {
|
||||
this.documents[i] = this.data.slice(this.index, this.index + bsonSize);
|
||||
} else {
|
||||
this.documents[i] = this.bson.deserialize(
|
||||
this.data.slice(this.index, this.index + bsonSize),
|
||||
_options
|
||||
);
|
||||
}
|
||||
|
||||
// Adjust the index
|
||||
this.index = this.index + bsonSize;
|
||||
}
|
||||
|
||||
if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
|
||||
const fieldsAsRaw = {};
|
||||
fieldsAsRaw[documentsReturnedIn] = true;
|
||||
_options.fieldsAsRaw = fieldsAsRaw;
|
||||
|
||||
const doc = this.bson.deserialize(this.documents[0], _options);
|
||||
this.documents = [doc];
|
||||
}
|
||||
|
||||
// Set parsed
|
||||
this.parsed = true;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
Query: Query,
|
||||
GetMore: GetMore,
|
||||
Response: Response,
|
||||
KillCursor: KillCursor
|
||||
};
|
||||
-358
@@ -1,358 +0,0 @@
|
||||
'use strict';
|
||||
const net = require('net');
|
||||
const tls = require('tls');
|
||||
const Connection = require('./connection');
|
||||
const Query = require('./commands').Query;
|
||||
const createClientInfo = require('../topologies/shared').createClientInfo;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders;
|
||||
const WIRE_CONSTANTS = require('../wireprotocol/constants');
|
||||
const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
|
||||
const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
|
||||
const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
|
||||
const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
|
||||
let AUTH_PROVIDERS;
|
||||
|
||||
function connect(options, callback) {
|
||||
if (AUTH_PROVIDERS == null) {
|
||||
AUTH_PROVIDERS = defaultAuthProviders(options.bson);
|
||||
}
|
||||
|
||||
if (options.family !== void 0) {
|
||||
makeConnection(options.family, options, (err, socket) => {
|
||||
if (err) {
|
||||
callback(err, socket); // in the error case, `socket` is the originating error event name
|
||||
return;
|
||||
}
|
||||
|
||||
performInitialHandshake(new Connection(socket, options), options, callback);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return makeConnection(6, options, (err, ipv6Socket) => {
|
||||
if (err) {
|
||||
makeConnection(4, options, (err, ipv4Socket) => {
|
||||
if (err) {
|
||||
callback(err, ipv4Socket); // in the error case, `ipv4Socket` is the originating error event name
|
||||
return;
|
||||
}
|
||||
|
||||
performInitialHandshake(new Connection(ipv4Socket, options), options, callback);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
performInitialHandshake(new Connection(ipv6Socket, options), options, callback);
|
||||
});
|
||||
}
|
||||
|
||||
function getSaslSupportedMechs(options) {
|
||||
if (!(options && options.credentials)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const credentials = options.credentials;
|
||||
|
||||
// TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here
|
||||
const authMechanism = credentials.mechanism;
|
||||
const authSource = credentials.source || options.dbName || 'admin';
|
||||
const user = credentials.username || options.user;
|
||||
|
||||
if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return { saslSupportedMechs: `${authSource}.${user}` };
|
||||
}
|
||||
|
||||
function checkSupportedServer(ismaster, options) {
|
||||
const serverVersionHighEnough =
|
||||
ismaster &&
|
||||
typeof ismaster.maxWireVersion === 'number' &&
|
||||
ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION;
|
||||
const serverVersionLowEnough =
|
||||
ismaster &&
|
||||
typeof ismaster.minWireVersion === 'number' &&
|
||||
ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION;
|
||||
|
||||
if (serverVersionHighEnough) {
|
||||
if (serverVersionLowEnough) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const message = `Server at ${options.host}:${options.port} reports minimum wire version ${
|
||||
ismaster.minWireVersion
|
||||
}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;
|
||||
return new MongoError(message);
|
||||
}
|
||||
|
||||
const message = `Server at ${options.host}:${
|
||||
options.port
|
||||
} reports maximum wire version ${ismaster.maxWireVersion ||
|
||||
0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`;
|
||||
return new MongoError(message);
|
||||
}
|
||||
|
||||
function performInitialHandshake(conn, options, _callback) {
|
||||
const callback = function(err, ret) {
|
||||
if (err && conn) {
|
||||
conn.destroy();
|
||||
}
|
||||
_callback(err, ret);
|
||||
};
|
||||
|
||||
let compressors = [];
|
||||
if (options.compression && options.compression.compressors) {
|
||||
compressors = options.compression.compressors;
|
||||
}
|
||||
|
||||
const handshakeDoc = Object.assign(
|
||||
{
|
||||
ismaster: true,
|
||||
client: createClientInfo(options),
|
||||
compression: compressors
|
||||
},
|
||||
getSaslSupportedMechs(options)
|
||||
);
|
||||
|
||||
const start = new Date().getTime();
|
||||
runCommand(conn, 'admin.$cmd', handshakeDoc, options, (err, ismaster) => {
|
||||
if (err) {
|
||||
callback(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ismaster.ok === 0) {
|
||||
callback(new MongoError(ismaster), null);
|
||||
return;
|
||||
}
|
||||
|
||||
const supportedServerErr = checkSupportedServer(ismaster, options);
|
||||
if (supportedServerErr) {
|
||||
callback(supportedServerErr, null);
|
||||
return;
|
||||
}
|
||||
|
||||
// resolve compression
|
||||
if (ismaster.compression) {
|
||||
const agreedCompressors = compressors.filter(
|
||||
compressor => ismaster.compression.indexOf(compressor) !== -1
|
||||
);
|
||||
|
||||
if (agreedCompressors.length) {
|
||||
conn.agreedCompressor = agreedCompressors[0];
|
||||
}
|
||||
|
||||
if (options.compression && options.compression.zlibCompressionLevel) {
|
||||
conn.zlibCompressionLevel = options.compression.zlibCompressionLevel;
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: This is metadata attached to the connection while porting away from
|
||||
// handshake being done in the `Server` class. Likely, it should be
|
||||
// relocated, or at very least restructured.
|
||||
conn.ismaster = ismaster;
|
||||
conn.lastIsMasterMS = new Date().getTime() - start;
|
||||
|
||||
const credentials = options.credentials;
|
||||
if (!ismaster.arbiterOnly && credentials) {
|
||||
credentials.resolveAuthMechanism(ismaster);
|
||||
authenticate(conn, credentials, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(null, conn);
|
||||
});
|
||||
}
|
||||
|
||||
const LEGAL_SSL_SOCKET_OPTIONS = [
|
||||
'pfx',
|
||||
'key',
|
||||
'passphrase',
|
||||
'cert',
|
||||
'ca',
|
||||
'ciphers',
|
||||
'NPNProtocols',
|
||||
'ALPNProtocols',
|
||||
'servername',
|
||||
'ecdhCurve',
|
||||
'secureProtocol',
|
||||
'secureContext',
|
||||
'session',
|
||||
'minDHSize',
|
||||
'crl',
|
||||
'rejectUnauthorized'
|
||||
];
|
||||
|
||||
function parseConnectOptions(family, options) {
|
||||
const host = typeof options.host === 'string' ? options.host : 'localhost';
|
||||
if (host.indexOf('/') !== -1) {
|
||||
return { path: host };
|
||||
}
|
||||
|
||||
const result = {
|
||||
family,
|
||||
host,
|
||||
port: typeof options.port === 'number' ? options.port : 27017,
|
||||
rejectUnauthorized: false
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseSslOptions(family, options) {
|
||||
const result = parseConnectOptions(family, options);
|
||||
|
||||
// Merge in valid SSL options
|
||||
for (const name in options) {
|
||||
if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) {
|
||||
result[name] = options[name];
|
||||
}
|
||||
}
|
||||
|
||||
// Override checkServerIdentity behavior
|
||||
if (options.checkServerIdentity === false) {
|
||||
// Skip the identiy check by retuning undefined as per node documents
|
||||
// https://nodejs.org/api/tls.html#tls_tls_connect_options_callback
|
||||
result.checkServerIdentity = function() {
|
||||
return undefined;
|
||||
};
|
||||
} else if (typeof options.checkServerIdentity === 'function') {
|
||||
result.checkServerIdentity = options.checkServerIdentity;
|
||||
}
|
||||
|
||||
// Set default sni servername to be the same as host
|
||||
if (result.servername == null) {
|
||||
result.servername = result.host;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function makeConnection(family, options, _callback) {
|
||||
const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false;
|
||||
const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;
|
||||
let keepAliveInitialDelay =
|
||||
typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000;
|
||||
const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true;
|
||||
const connectionTimeout =
|
||||
typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000;
|
||||
const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
const rejectUnauthorized =
|
||||
typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true;
|
||||
|
||||
if (keepAliveInitialDelay > socketTimeout) {
|
||||
keepAliveInitialDelay = Math.round(socketTimeout / 2);
|
||||
}
|
||||
|
||||
let socket;
|
||||
const callback = function(err, ret) {
|
||||
if (err && socket) {
|
||||
socket.destroy();
|
||||
}
|
||||
_callback(err, ret);
|
||||
};
|
||||
|
||||
try {
|
||||
if (useSsl) {
|
||||
socket = tls.connect(parseSslOptions(family, options));
|
||||
if (typeof socket.disableRenegotiation === 'function') {
|
||||
socket.disableRenegotiation();
|
||||
}
|
||||
} else {
|
||||
socket = net.createConnection(parseConnectOptions(family, options));
|
||||
}
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
socket.setKeepAlive(keepAlive, keepAliveInitialDelay);
|
||||
socket.setTimeout(connectionTimeout);
|
||||
socket.setNoDelay(noDelay);
|
||||
|
||||
const errorEvents = ['error', 'close', 'timeout', 'parseError', 'connect'];
|
||||
function errorHandler(eventName) {
|
||||
return err => {
|
||||
if (err == null || err === false) err = true;
|
||||
errorEvents.forEach(event => socket.removeAllListeners(event));
|
||||
socket.removeListener('connect', connectHandler);
|
||||
callback(new MongoNetworkError(err.message), eventName);
|
||||
};
|
||||
}
|
||||
|
||||
function connectHandler() {
|
||||
errorEvents.forEach(event => socket.removeAllListeners(event));
|
||||
if (socket.authorizationError && rejectUnauthorized) {
|
||||
return callback(socket.authorizationError);
|
||||
}
|
||||
|
||||
socket.setTimeout(socketTimeout);
|
||||
callback(null, socket);
|
||||
}
|
||||
|
||||
socket.once('error', errorHandler('error'));
|
||||
socket.once('close', errorHandler('close'));
|
||||
socket.once('timeout', errorHandler('timeout'));
|
||||
socket.once('parseError', errorHandler('parseError'));
|
||||
socket.once('connect', connectHandler);
|
||||
}
|
||||
|
||||
const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError'];
|
||||
function runCommand(conn, ns, command, options, callback) {
|
||||
if (typeof options === 'function') (callback = options), (options = {});
|
||||
const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
const bson = conn.options.bson;
|
||||
const query = new Query(bson, ns, command, {
|
||||
numberToSkip: 0,
|
||||
numberToReturn: 1
|
||||
});
|
||||
|
||||
function errorHandler(err) {
|
||||
conn.resetSocketTimeout();
|
||||
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));
|
||||
conn.removeListener('message', messageHandler);
|
||||
callback(err, null);
|
||||
}
|
||||
|
||||
function messageHandler(msg) {
|
||||
if (msg.responseTo !== query.requestId) {
|
||||
return;
|
||||
}
|
||||
|
||||
conn.resetSocketTimeout();
|
||||
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler));
|
||||
conn.removeListener('message', messageHandler);
|
||||
|
||||
msg.parse({ promoteValues: true });
|
||||
callback(null, msg.documents[0]);
|
||||
}
|
||||
|
||||
conn.setSocketTimeout(socketTimeout);
|
||||
CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler));
|
||||
conn.on('message', messageHandler);
|
||||
conn.write(query.toBin());
|
||||
}
|
||||
|
||||
function authenticate(conn, credentials, callback) {
|
||||
const mechanism = credentials.mechanism;
|
||||
if (!AUTH_PROVIDERS[mechanism]) {
|
||||
callback(new MongoError(`authMechanism '${mechanism}' not supported`));
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = AUTH_PROVIDERS[mechanism];
|
||||
provider.auth(runCommand, [conn], credentials, err => {
|
||||
if (err) return callback(err);
|
||||
callback(null, conn);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = connect;
|
||||
-624
@@ -1,624 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const crypto = require('crypto');
|
||||
const debugOptions = require('./utils').debugOptions;
|
||||
const parseHeader = require('../wireprotocol/shared').parseHeader;
|
||||
const decompress = require('../wireprotocol/compression').decompress;
|
||||
const Response = require('./commands').Response;
|
||||
const BinMsg = require('./msg').BinMsg;
|
||||
const MongoNetworkError = require('../error').MongoNetworkError;
|
||||
const MongoError = require('../error').MongoError;
|
||||
const Logger = require('./logger');
|
||||
const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED;
|
||||
const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG;
|
||||
const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE;
|
||||
const Buffer = require('safe-buffer').Buffer;
|
||||
|
||||
let _id = 0;
|
||||
|
||||
const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4;
|
||||
const DEBUG_FIELDS = [
|
||||
'host',
|
||||
'port',
|
||||
'size',
|
||||
'keepAlive',
|
||||
'keepAliveInitialDelay',
|
||||
'noDelay',
|
||||
'connectionTimeout',
|
||||
'socketTimeout',
|
||||
'ssl',
|
||||
'ca',
|
||||
'crl',
|
||||
'cert',
|
||||
'rejectUnauthorized',
|
||||
'promoteLongs',
|
||||
'promoteValues',
|
||||
'promoteBuffers',
|
||||
'checkServerIdentity'
|
||||
];
|
||||
|
||||
let connectionAccountingSpy = undefined;
|
||||
let connectionAccounting = false;
|
||||
let connections = {};
|
||||
|
||||
/**
|
||||
* A class representing a single connection to a MongoDB server
|
||||
*
|
||||
* @fires Connection#connect
|
||||
* @fires Connection#close
|
||||
* @fires Connection#error
|
||||
* @fires Connection#timeout
|
||||
* @fires Connection#parseError
|
||||
* @fires Connection#message
|
||||
*/
|
||||
class Connection extends EventEmitter {
|
||||
/**
|
||||
* Creates a new Connection instance
|
||||
*
|
||||
* @param {Socket} socket The socket this connection wraps
|
||||
* @param {Object} [options] Optional settings
|
||||
* @param {string} [options.host] The host the socket is connected to
|
||||
* @param {number} [options.port] The port used for the socket connection
|
||||
* @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
|
||||
* @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled
|
||||
* @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
|
||||
* @param {number} [options.socketTimeout=360000] TCP Socket timeout setting
|
||||
* @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits
|
||||
* @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
|
||||
* @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers.
|
||||
*/
|
||||
constructor(socket, options) {
|
||||
super();
|
||||
|
||||
options = options || {};
|
||||
if (!options.bson) {
|
||||
throw new TypeError('must pass in valid bson parser');
|
||||
}
|
||||
|
||||
this.id = _id++;
|
||||
this.options = options;
|
||||
this.logger = Logger('Connection', options);
|
||||
this.bson = options.bson;
|
||||
this.tag = options.tag;
|
||||
this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE;
|
||||
|
||||
this.port = options.port || 27017;
|
||||
this.host = options.host || 'localhost';
|
||||
this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000;
|
||||
|
||||
// These values are inspected directly in tests, but maybe not necessary to keep around
|
||||
this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true;
|
||||
this.keepAliveInitialDelay =
|
||||
typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000;
|
||||
this.connectionTimeout =
|
||||
typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000;
|
||||
if (this.keepAliveInitialDelay > this.socketTimeout) {
|
||||
this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2);
|
||||
}
|
||||
|
||||
// Debug information
|
||||
if (this.logger.isDebug()) {
|
||||
this.logger.debug(
|
||||
`creating connection ${this.id} with options [${JSON.stringify(
|
||||
debugOptions(DEBUG_FIELDS, options)
|
||||
)}]`
|
||||
);
|
||||
}
|
||||
|
||||
// Response options
|
||||
this.responseOptions = {
|
||||
promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true,
|
||||
promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true,
|
||||
promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false
|
||||
};
|
||||
|
||||
// Flushing
|
||||
this.flushing = false;
|
||||
this.queue = [];
|
||||
|
||||
// Internal state
|
||||
this.writeStream = null;
|
||||
this.destroyed = false;
|
||||
|
||||
// Create hash method
|
||||
const hash = crypto.createHash('sha1');
|
||||
hash.update(this.address);
|
||||
this.hashedName = hash.digest('hex');
|
||||
|
||||
// All operations in flight on the connection
|
||||
this.workItems = [];
|
||||
|
||||
// setup socket
|
||||
this.socket = socket;
|
||||
this.socket.once('error', errorHandler(this));
|
||||
this.socket.once('timeout', timeoutHandler(this));
|
||||
this.socket.once('close', closeHandler(this));
|
||||
this.socket.on('data', dataHandler(this));
|
||||
|
||||
if (connectionAccounting) {
|
||||
addConnection(this.id, this);
|
||||
}
|
||||
}
|
||||
|
||||
setSocketTimeout(value) {
|
||||
if (this.socket) {
|
||||
this.socket.setTimeout(value);
|
||||
}
|
||||
}
|
||||
|
||||
resetSocketTimeout() {
|
||||
if (this.socket) {
|
||||
this.socket.setTimeout(this.socketTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
static enableConnectionAccounting(spy) {
|
||||
if (spy) {
|
||||
connectionAccountingSpy = spy;
|
||||
}
|
||||
|
||||
connectionAccounting = true;
|
||||
connections = {};
|
||||
}
|
||||
|
||||
static disableConnectionAccounting() {
|
||||
connectionAccounting = false;
|
||||
connectionAccountingSpy = undefined;
|
||||
}
|
||||
|
||||
static connections() {
|
||||
return connections;
|
||||
}
|
||||
|
||||
get address() {
|
||||
return `${this.host}:${this.port}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unref this connection
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
unref() {
|
||||
if (this.socket == null) {
|
||||
this.once('connect', () => this.socket.unref());
|
||||
return;
|
||||
}
|
||||
|
||||
this.socket.unref();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy connection
|
||||
* @method
|
||||
*/
|
||||
destroy(options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
options = Object.assign({ force: false }, options);
|
||||
|
||||
if (connectionAccounting) {
|
||||
deleteConnection(this.id);
|
||||
}
|
||||
|
||||
if (this.socket == null) {
|
||||
this.destroyed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.force) {
|
||||
this.socket.destroy();
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') callback(null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
this.socket.end(err => {
|
||||
this.destroyed = true;
|
||||
if (typeof callback === 'function') callback(err, null);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write to connection
|
||||
* @method
|
||||
* @param {Command} command Command to write out need to implement toBin and toBinUnified
|
||||
*/
|
||||
write(buffer) {
|
||||
// Debug Log
|
||||
if (this.logger.isDebug()) {
|
||||
if (!Array.isArray(buffer)) {
|
||||
this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`);
|
||||
} else {
|
||||
for (let i = 0; i < buffer.length; i++)
|
||||
this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Double check that the connection is not destroyed
|
||||
if (this.socket.destroyed === false) {
|
||||
// Write out the command
|
||||
if (!Array.isArray(buffer)) {
|
||||
this.socket.write(buffer, 'binary');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Iterate over all buffers and write them in order to the socket
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
this.socket.write(buffer[i], 'binary');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Connection is destroyed return write failed
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return id of connection as a string
|
||||
* @method
|
||||
* @return {string}
|
||||
*/
|
||||
toString() {
|
||||
return '' + this.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return json object of connection
|
||||
* @method
|
||||
* @return {object}
|
||||
*/
|
||||
toJSON() {
|
||||
return { id: this.id, host: this.host, port: this.port };
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the connection connected
|
||||
* @method
|
||||
* @return {boolean}
|
||||
*/
|
||||
isConnected() {
|
||||
if (this.destroyed) return false;
|
||||
return !this.socket.destroyed && this.socket.writable;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteConnection(id) {
|
||||
// console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : ''))
|
||||
delete connections[id];
|
||||
|
||||
if (connectionAccountingSpy) {
|
||||
connectionAccountingSpy.deleteConnection(id);
|
||||
}
|
||||
}
|
||||
|
||||
function addConnection(id, connection) {
|
||||
// console.log("=== added connection " + id + " :: " + connection.port)
|
||||
connections[id] = connection;
|
||||
|
||||
if (connectionAccountingSpy) {
|
||||
connectionAccountingSpy.addConnection(id, connection);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Connection handlers
|
||||
function errorHandler(conn) {
|
||||
return function(err) {
|
||||
if (connectionAccounting) deleteConnection(conn.id);
|
||||
// Debug information
|
||||
if (conn.logger.isDebug()) {
|
||||
conn.logger.debug(
|
||||
`connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]`
|
||||
);
|
||||
}
|
||||
|
||||
conn.emit('error', new MongoNetworkError(err), conn);
|
||||
};
|
||||
}
|
||||
|
||||
function timeoutHandler(conn) {
|
||||
return function() {
|
||||
if (connectionAccounting) deleteConnection(conn.id);
|
||||
|
||||
if (conn.logger.isDebug()) {
|
||||
conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`);
|
||||
}
|
||||
|
||||
conn.emit(
|
||||
'timeout',
|
||||
new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`),
|
||||
conn
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function closeHandler(conn) {
|
||||
return function(hadError) {
|
||||
if (connectionAccounting) deleteConnection(conn.id);
|
||||
|
||||
if (conn.logger.isDebug()) {
|
||||
conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`);
|
||||
}
|
||||
|
||||
if (!hadError) {
|
||||
conn.emit(
|
||||
'close',
|
||||
new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`),
|
||||
conn
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Handle a message once it is received
|
||||
function processMessage(conn, message) {
|
||||
const msgHeader = parseHeader(message);
|
||||
if (msgHeader.opCode !== OP_COMPRESSED) {
|
||||
const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;
|
||||
conn.emit(
|
||||
'message',
|
||||
new ResponseConstructor(
|
||||
conn.bson,
|
||||
message,
|
||||
msgHeader,
|
||||
message.slice(MESSAGE_HEADER_SIZE),
|
||||
conn.responseOptions
|
||||
),
|
||||
conn
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
msgHeader.fromCompressed = true;
|
||||
let index = MESSAGE_HEADER_SIZE;
|
||||
msgHeader.opCode = message.readInt32LE(index);
|
||||
index += 4;
|
||||
msgHeader.length = message.readInt32LE(index);
|
||||
index += 4;
|
||||
const compressorID = message[index];
|
||||
index++;
|
||||
|
||||
decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => {
|
||||
if (err) {
|
||||
conn.emit('error', err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (decompressedMsgBody.length !== msgHeader.length) {
|
||||
conn.emit(
|
||||
'error',
|
||||
new MongoError(
|
||||
'Decompressing a compressed message from the server failed. The message is corrupt.'
|
||||
)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response;
|
||||
conn.emit(
|
||||
'message',
|
||||
new ResponseConstructor(
|
||||
conn.bson,
|
||||
message,
|
||||
msgHeader,
|
||||
decompressedMsgBody,
|
||||
conn.responseOptions
|
||||
),
|
||||
conn
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function dataHandler(conn) {
|
||||
return function(data) {
|
||||
// Parse until we are done with the data
|
||||
while (data.length > 0) {
|
||||
// If we still have bytes to read on the current message
|
||||
if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) {
|
||||
// Calculate the amount of remaining bytes
|
||||
const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead;
|
||||
// Check if the current chunk contains the rest of the message
|
||||
if (remainingBytesToRead > data.length) {
|
||||
// Copy the new data into the exiting buffer (should have been allocated when we know the message size)
|
||||
data.copy(conn.buffer, conn.bytesRead);
|
||||
// Adjust the number of bytes read so it point to the correct index in the buffer
|
||||
conn.bytesRead = conn.bytesRead + data.length;
|
||||
|
||||
// Reset state of buffer
|
||||
data = Buffer.alloc(0);
|
||||
} else {
|
||||
// Copy the missing part of the data into our current buffer
|
||||
data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead);
|
||||
// Slice the overflow into a new buffer that we will then re-parse
|
||||
data = data.slice(remainingBytesToRead);
|
||||
|
||||
// Emit current complete message
|
||||
const emitBuffer = conn.buffer;
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
|
||||
processMessage(conn, emitBuffer);
|
||||
}
|
||||
} else {
|
||||
// Stub buffer is kept in case we don't get enough bytes to determine the
|
||||
// size of the message (< 4 bytes)
|
||||
if (conn.stubBuffer != null && conn.stubBuffer.length > 0) {
|
||||
// If we have enough bytes to determine the message size let's do it
|
||||
if (conn.stubBuffer.length + data.length > 4) {
|
||||
// Prepad the data
|
||||
const newData = Buffer.alloc(conn.stubBuffer.length + data.length);
|
||||
conn.stubBuffer.copy(newData, 0);
|
||||
data.copy(newData, conn.stubBuffer.length);
|
||||
// Reassign for parsing
|
||||
data = newData;
|
||||
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
} else {
|
||||
// Add the the bytes to the stub buffer
|
||||
const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length);
|
||||
// Copy existing stub buffer
|
||||
conn.stubBuffer.copy(newStubBuffer, 0);
|
||||
// Copy missing part of the data
|
||||
data.copy(newStubBuffer, conn.stubBuffer.length);
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
}
|
||||
} else {
|
||||
if (data.length > 4) {
|
||||
// Retrieve the message size
|
||||
const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
|
||||
// If we have a negative sizeOfMessage emit error and return
|
||||
if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) {
|
||||
const errorObject = {
|
||||
err: 'socketHandler',
|
||||
trace: '',
|
||||
bin: conn.buffer,
|
||||
parseState: {
|
||||
sizeOfMessage: sizeOfMessage,
|
||||
bytesRead: conn.bytesRead,
|
||||
stubBuffer: conn.stubBuffer
|
||||
}
|
||||
};
|
||||
// We got a parse Error fire it off then keep going
|
||||
conn.emit('parseError', errorObject, conn);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure that the size of message is larger than 0 and less than the max allowed
|
||||
if (
|
||||
sizeOfMessage > 4 &&
|
||||
sizeOfMessage < conn.maxBsonMessageSize &&
|
||||
sizeOfMessage > data.length
|
||||
) {
|
||||
conn.buffer = Buffer.alloc(sizeOfMessage);
|
||||
// Copy all the data into the buffer
|
||||
data.copy(conn.buffer, 0);
|
||||
// Update bytes read
|
||||
conn.bytesRead = data.length;
|
||||
// Update sizeOfMessage
|
||||
conn.sizeOfMessage = sizeOfMessage;
|
||||
// Ensure stub buffer is null
|
||||
conn.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
} else if (
|
||||
sizeOfMessage > 4 &&
|
||||
sizeOfMessage < conn.maxBsonMessageSize &&
|
||||
sizeOfMessage === data.length
|
||||
) {
|
||||
const emitBuffer = data;
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
// Emit the message
|
||||
processMessage(conn, emitBuffer);
|
||||
} else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) {
|
||||
const errorObject = {
|
||||
err: 'socketHandler',
|
||||
trace: null,
|
||||
bin: data,
|
||||
parseState: {
|
||||
sizeOfMessage: sizeOfMessage,
|
||||
bytesRead: 0,
|
||||
buffer: null,
|
||||
stubBuffer: null
|
||||
}
|
||||
};
|
||||
// We got a parse Error fire it off then keep going
|
||||
conn.emit('parseError', errorObject, conn);
|
||||
|
||||
// Clear out the state of the parser
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
} else {
|
||||
const emitBuffer = data.slice(0, sizeOfMessage);
|
||||
// Reset state of buffer
|
||||
conn.buffer = null;
|
||||
conn.sizeOfMessage = 0;
|
||||
conn.bytesRead = 0;
|
||||
conn.stubBuffer = null;
|
||||
// Copy rest of message
|
||||
data = data.slice(sizeOfMessage);
|
||||
// Emit the message
|
||||
processMessage(conn, emitBuffer);
|
||||
}
|
||||
} else {
|
||||
// Create a buffer that contains the space for the non-complete message
|
||||
conn.stubBuffer = Buffer.alloc(data.length);
|
||||
// Copy the data to the stub buffer
|
||||
data.copy(conn.stubBuffer, 0);
|
||||
// Exit parsing loop
|
||||
data = Buffer.alloc(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A server connect event, used to verify that the connection is up and running
|
||||
*
|
||||
* @event Connection#connect
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The server connection closed, all pool connections closed
|
||||
*
|
||||
* @event Connection#close
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The server connection caused an error, all pool connections closed
|
||||
*
|
||||
* @event Connection#error
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The server connection timed out, all pool connections closed
|
||||
*
|
||||
* @event Connection#timeout
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The driver experienced an invalid message, all pool connections closed
|
||||
*
|
||||
* @event Connection#parseError
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An event emitted each time the connection receives a parsed message from the wire
|
||||
*
|
||||
* @event Connection#message
|
||||
* @type {Connection}
|
||||
*/
|
||||
|
||||
module.exports = Connection;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user