Skip to content

Commit 64a9b8d

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 a9d10eb commit 64a9b8d

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
@@ -521,11 +521,15 @@ function applyFilter(filter) {
521521
// then, we attempt to emulate mongo db matching. Helps for embedded relations
522522
var dotIndex = key.indexOf('.');
523523
var subValue = obj[key.substring(0, dotIndex)];
524-
if (dotIndex !== -1 && Array.isArray(subValue)) {
524+
if (dotIndex !== -1) {
525525
var subFilter = { where: {}};
526526
var subKey = key.substring(dotIndex + 1);
527527
subFilter.where[subKey] = where[key];
528-
return subValue.some(applyFilter(subFilter));
528+
if (Array.isArray(subValue)) {
529+
return subValue.some(applyFilter(subFilter));
530+
} else if (typeof subValue === 'object' && subValue !== null) {
531+
return applyFilter(subFilter)(subValue);
532+
}
529533
}
530534

531535
return false;

test/memory.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,11 @@ describe('Memory connector', function() {
156156
city: String,
157157
state: String,
158158
zipCode: String,
159+
tags: [
160+
{
161+
tag: String,
162+
},
163+
],
159164
},
160165
friends: [
161166
{
@@ -523,6 +528,16 @@ describe('Memory connector', function() {
523528
});
524529
});
525530

531+
it('should support multi-level nested array property in query', function(done) {
532+
User.find({ where: { 'address.tags.tag': 'business' }}, function(err, users) {
533+
should.not.exist(err);
534+
users.length.should.be.equal(1);
535+
users[0].address.tags[0].tag.should.be.equal('business');
536+
users[0].address.tags[1].tag.should.be.equal('rent');
537+
done();
538+
});
539+
});
540+
526541
function seed(done) {
527542
var beatles = [
528543
{
@@ -537,6 +552,10 @@ describe('Memory connector', function() {
537552
city: 'San Jose',
538553
state: 'CA',
539554
zipCode: '95131',
555+
tags: [
556+
{ tag: 'business' },
557+
{ tag: 'rent' },
558+
],
540559
},
541560
friends: [
542561
{ name: 'Paul McCartney' },

0 commit comments

Comments
 (0)