Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waterline/Sails.js/Mongo How to use AND conditions in query for one filed?

My question is same to Waterline (Sails.js): AND conditions. There is a answer but it's not work for me (neither for the questioner).

As far as I know , waterline doesn't have keyword 'and' in its query language. If I have multiple conditions to query, I can simply use:

MyModel.find({fieldA:valueA, filedB:valueB});

But my question is how to do:

MyModel.find({fieldA:{
   contains:keyword1, 
   contains:keyword2
}});

For I can't set two key with same name in Object/JSON, so I tried :

MyModel.find({fieldA:
  [
   {contains:keyword1}, 
   {contains:keyword2}
  ]
});

and

MyModel.find({fieldA:
  {contains:[keyword1,keyword2]}
});

and

MyModel.find()
.where({fieldA:{contains:keyword1})
.where({fieldA:{contains:keyword2}});

But none of them work as expected : 1st and 2nd one returns empty set and 3rd one only contains keyword2. It appears that when you trying to add two 'contains' condition to a same filed(fieldA), with chained 'where' method, the second one will overwrite the first one.

I'm using the native mongoDB's way to handle this as a workaround, Dose anyone know how to do this in waterline's way ? Or is this a issue should be reported on github.

PS:sorry for my poor English :p

like image 682
Giyya Pan Avatar asked Jan 09 '23 11:01

Giyya Pan


1 Answers

To answer your question, multiple contains are not supported. Whether it's an omission or a feature request is debatable. At least for an SQL case, it's a stupid simple fix (though took me over an hour to find it) to be able to support something like:

orm.collections.user.find({
            and: [
                { name: { contains: 'neil' } },
                { name: { contains: 'armstrong' } }
            ]
        });

All it needs is a case 'and': in in the following file and it works:

https://github.com/balderdashy/waterline-sequel/blob/master/sequel/lib/criteriaProcessor.js#L120

I suspect the Mongo case would be similar.

like image 184
Andrew Eddie Avatar answered May 16 '23 07:05

Andrew Eddie