Skip to content

Commit

Permalink
feat: basic PoC of Map type re: #681
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Mar 27, 2018
1 parent a5566a4 commit f828de3
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/schema/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ exports.Mixed = require('./mixed');

exports.Decimal128 = exports.Decimal = require('./decimal128');

exports.Map = require('./map');

// alias

exports.Oid = exports.ObjectId;
Expand Down
25 changes: 25 additions & 0 deletions lib/schema/map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*!
* ignore
*/

const MongooseMap = require('../types/map');
const SchemaType = require('../schematype');

/*!
* ignore
*/

class SchemaMap extends SchemaType {
constructor(key, options) {
super(key, options, 'Map');
}

cast(val, doc) {
if (val instanceof MongooseMap) {
return val;
}
return new MongooseMap(val, this.path, doc);
}
}

module.exports = SchemaMap;
2 changes: 2 additions & 0 deletions lib/types/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ exports.DocumentArray = require('./documentarray');
exports.Decimal128 = require('./decimal128');
exports.ObjectId = require('./objectid');

exports.Map = require('./map');

exports.Subdocument = require('./subdocument');
45 changes: 45 additions & 0 deletions lib/types/map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*!
* ignore
*/

class MongooseMap extends Map {
constructor(v, path, doc) {
if (v != null && v.constructor.name === 'Object') {
v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []);
}
super(v);

this.$__parent = doc;
this.$__path = path;
}

set(key, value) {
super.set(key, value);

if (this.$__parent != null) {
this.$__parent.markModified(this.$__path + '.' + key);
}
}

toBSON() {
return new Map(this);
}

toJSON() {
return new Map(this);
}
}

Object.defineProperty(MongooseMap.prototype, '$__parent', {
enumerable: false,
writable: true,
configurable: false
});

Object.defineProperty(MongooseMap.prototype, '$__path', {
enumerable: false,
writable: true,
configurable: false
});

module.exports = MongooseMap;

0 comments on commit f828de3

Please sign in to comment.