Skip to content

Commit a39c023

Browse files
pponugobajtos
authored andcommitted
Support nested queries for arrays
Enhance the built-in memory connector to correctly support nested queries for arrays in addition to objects. E.g. if "friends" is an array of objects containing "name", then { where: { "friends.name": "Jane" } } should match records containing a friend called "Jane".
1 parent 19dae30 commit a39c023

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

lib/connectors/memory.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -523,11 +523,15 @@ function applyFilter(filter) {
523523
// then, we attempt to emulate mongo db matching. Helps for embedded relations
524524
var dotIndex = key.indexOf('.');
525525
var subValue = obj[key.substring(0, dotIndex)];
526-
if (dotIndex !== -1 && Array.isArray(subValue)) {
526+
if (dotIndex !== -1) {
527527
var subFilter = {where: {}};
528528
var subKey = key.substring(dotIndex + 1);
529529
subFilter.where[subKey] = where[key];
530-
return subValue.some(applyFilter(subFilter));
530+
if (Array.isArray(subValue)) {
531+
return subValue.some(applyFilter(subFilter));
532+
} else if (typeof subValue === 'object' && subValue !== null) {
533+
return applyFilter(subFilter)(subValue);
534+
}
531535
}
532536

533537
return false;

test/memory.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,11 @@ describe('Memory connector', function() {
158158
city: String,
159159
state: String,
160160
zipCode: String,
161+
tags: [
162+
{
163+
tag: String,
164+
},
165+
],
161166
},
162167
friends: [
163168
{
@@ -542,6 +547,16 @@ describe('Memory connector', function() {
542547
});
543548
});
544549

550+
it('should support multi-level nested array property in query', function(done) {
551+
User.find({where: {'address.tags.tag': 'business'}}, function(err, users) {
552+
should.not.exist(err);
553+
users.length.should.be.equal(1);
554+
users[0].address.tags[0].tag.should.be.equal('business');
555+
users[0].address.tags[1].tag.should.be.equal('rent');
556+
done();
557+
});
558+
});
559+
545560
function seed(done) {
546561
var beatles = [
547562
{
@@ -556,6 +571,10 @@ describe('Memory connector', function() {
556571
city: 'San Jose',
557572
state: 'CA',
558573
zipCode: '95131',
574+
tags: [
575+
{tag: 'business'},
576+
{tag: 'rent'},
577+
],
559578
},
560579
friends: [
561580
{name: 'Paul McCartney'},

0 commit comments

Comments
 (0)