Skip to content

Commit

Permalink
fixed; casting docs with String,Number,Buffer _ids
Browse files Browse the repository at this point in the history
Schema({ fans: [String] })
new Doc({ fans: [{ _id: "miami" }, { _id: "trump" }] })
  • Loading branch information
aheckmann committed Feb 3, 2013
1 parent 6813357 commit f8f2dd7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 12 deletions.
5 changes: 5 additions & 0 deletions lib/schema/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ SchemaBuffer.prototype.checkRequired = function (value) {
SchemaBuffer.prototype.cast = function (value, doc, init) {
if (SchemaType._isRef(this, value, init)) return value;

// documents with Buffer _ids
if (value && Buffer.isBuffer(value._id)) {
value = value._id;
}

if (Buffer.isBuffer(value)) {
if (!(value instanceof MongooseBuffer)) {
value = new MongooseBuffer(value, [this.path, doc]);
Expand Down
22 changes: 13 additions & 9 deletions lib/schema/number.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,19 @@ SchemaNumber.prototype.max = function (value, message) {
SchemaNumber.prototype.cast = function (value, doc, init) {
if (SchemaType._isRef(this, value, init)) return value;

if (!isNaN(value)){
if (null === value) return value;
if ('' === value) return null;
if ('string' == typeof value) value = Number(value);
if (value instanceof Number) return value
if ('number' == typeof value) return value;
if (value.toString && !Array.isArray(value) &&
value.toString() == Number(value)) {
return new Number(value)
var val = value && value._id
? value._id // documents
: value;

if (!isNaN(val)){
if (null === val) return val;
if ('' === val) return null;
if ('string' == typeof val) val = Number(val);
if (val instanceof Number) return val
if ('number' == typeof val) return val;
if (val.toString && !Array.isArray(val) &&
val.toString() == Number(val)) {
return new Number(val)
}
}

Expand Down
22 changes: 19 additions & 3 deletions lib/schema/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,25 @@ SchemaString.prototype.checkRequired = function checkRequired (value) {
*/

SchemaString.prototype.cast = function (value, scope, init) {
if (SchemaType._isRef(this, value, init)) return value;
if (value === null) return value;
if ('undefined' !== typeof value && value.toString) return value.toString();
if (SchemaType._isRef(this, value, init)) {
return value;
}

if (value === null) {
return value;
}

if ('undefined' !== typeof value) {
// handle documents being passed
if (value._id && 'string' == typeof value._id) {
return value._id;
}
if (value.toString) {
return value.toString();
}
}


throw new CastError('string', value, this.path);
};

Expand Down

0 comments on commit f8f2dd7

Please sign in to comment.