Skip to content

Commit

Permalink
fix(map): support deep get/set
Browse files Browse the repository at this point in the history
Re: #681
  • Loading branch information
vkarpov15 committed Apr 17, 2018
1 parent da83ed2 commit df3858e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -969,7 +969,11 @@ Document.prototype.$__set = function(pathToMark, path, constructing, parts, sche
cur += (cur ? '.' + parts[i] : parts[i]);

if (last) {
obj[parts[i]] = val;
if (obj instanceof Map) {
obj.set(parts[i], val);
} else {
obj[parts[i]] = val;
}
} else {
if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') {
obj = obj[parts[i]];
Expand Down Expand Up @@ -1046,9 +1050,13 @@ Document.prototype.get = function(path, type, options) {
}

for (var i = 0, l = pieces.length; i < l; i++) {
obj = obj === null || obj === void 0
? undefined
: obj[pieces[i]];
if (obj == null) {
obj = void 0;
} else if (obj instanceof Map) {
obj = obj.get(pieces[i]);
} else {
obj = obj[pieces[i]];
}
}

if (adhoc) {
Expand Down
11 changes: 11 additions & 0 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,17 @@ Schema.prototype.pathType = function(path) {
return 'real';
}

// Look for maps
for (let _path of Object.keys(this.paths)) {
if (!_path.includes('.$*')) {
continue;
}
const re = new RegExp('^' + _path.replace(/\.\$\*/g, '.[^.]+') + '$');
if (re.test(path)) {
return this.paths[_path];
}
}

if (/\.\d+\.|\.\d+$/.test(path)) {
return getPositionalPathType(this, path);
}
Expand Down
20 changes: 20 additions & 0 deletions test/types.map.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,26 @@ describe('Map', function() {
});
});

it('deep set', function(done) {
const userSchema = new mongoose.Schema({
socialMediaHandles: {
type: Map,
of: String
}
});

const User = db.model('MapDeepSet', userSchema);

const user = new User({ socialMediaHandles: {} });

user.set('socialMediaHandles.github', 'vkarpov15');

assert.equal(user.socialMediaHandles.get('github'), 'vkarpov15');
assert.equal(user.get('socialMediaHandles.github'), 'vkarpov15');

done();
});

it('query casting', function() {
const TestSchema = new mongoose.Schema({
v: {
Expand Down

0 comments on commit df3858e

Please sign in to comment.