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".
This commit is contained in:
parent
19dae302a2
commit
a39c0236bb
|
@ -523,11 +523,15 @@ function applyFilter(filter) {
|
|||
// then, we attempt to emulate mongo db matching. Helps for embedded relations
|
||||
var dotIndex = key.indexOf('.');
|
||||
var subValue = obj[key.substring(0, dotIndex)];
|
||||
if (dotIndex !== -1 && Array.isArray(subValue)) {
|
||||
if (dotIndex !== -1) {
|
||||
var subFilter = {where: {}};
|
||||
var subKey = key.substring(dotIndex + 1);
|
||||
subFilter.where[subKey] = where[key];
|
||||
return subValue.some(applyFilter(subFilter));
|
||||
if (Array.isArray(subValue)) {
|
||||
return subValue.some(applyFilter(subFilter));
|
||||
} else if (typeof subValue === 'object' && subValue !== null) {
|
||||
return applyFilter(subFilter)(subValue);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
|
|
@ -158,6 +158,11 @@ describe('Memory connector', function() {
|
|||
city: String,
|
||||
state: String,
|
||||
zipCode: String,
|
||||
tags: [
|
||||
{
|
||||
tag: String,
|
||||
},
|
||||
],
|
||||
},
|
||||
friends: [
|
||||
{
|
||||
|
@ -542,6 +547,16 @@ describe('Memory connector', function() {
|
|||
});
|
||||
});
|
||||
|
||||
it('should support multi-level nested array property in query', function(done) {
|
||||
User.find({where: {'address.tags.tag': 'business'}}, function(err, users) {
|
||||
should.not.exist(err);
|
||||
users.length.should.be.equal(1);
|
||||
users[0].address.tags[0].tag.should.be.equal('business');
|
||||
users[0].address.tags[1].tag.should.be.equal('rent');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
function seed(done) {
|
||||
var beatles = [
|
||||
{
|
||||
|
@ -556,6 +571,10 @@ describe('Memory connector', function() {
|
|||
city: 'San Jose',
|
||||
state: 'CA',
|
||||
zipCode: '95131',
|
||||
tags: [
|
||||
{tag: 'business'},
|
||||
{tag: 'rent'},
|
||||
],
|
||||
},
|
||||
friends: [
|
||||
{name: 'Paul McCartney'},
|
||||
|
|
Loading…
Reference in New Issue