Start a new topic
Answered

How to efficiently fetch entities defined by list of ids?

I have a list of ids stored in array. I want to fetch entities with those ids. I can not see how to use the inline or nested or() operator in a for loop. 


Your documentation reads:


The example below demonstrates how to join two separate queries.

var query = new Kinvey.Query();query.equalTo('last_name', 'Doe');var secondQuery = new Kinvey.Query();secondQuery.equalTo('last_name', 'Roe')// Selects all users with last_name “Doe” or “Roe”.query.or(secondQuery);

Alternatively, the snippet above can be shortened using the join operator inline.

// Selects all users with last_name “Doe” or “Roe”.var query = new Kinvey.Query();query.equalTo('last_name', 'Doe').or().equalTo('last_name', 'Roe');



Best Answer

Hey Daniel,

I am able to implement your scenario using ternary operator.

See if the below snippet helps.
   
var names = ["Doe","Roe"];
var finalQuery;
for (var i =0; i < names.length; i++){
        var q = new Kinvey.Query().equalTo('name',names[i]);
        finalQuery = (finalQuery) ? finalQuery.or(q) : q;
    }
   
var promise = Kinvey.DataStore.find('collection-name', finalQuery);
promise.then(function(response) {
                ...           
    }, function(error) {
      ...
    });
   
   
Also a query like "new Kinvey.Query().equalTo('name','Doe').or()" would fetch all the entities.



Thanks,
Pranav
Kinvey Support


Answer

Hey Daniel,

I am able to implement your scenario using ternary operator.

See if the below snippet helps.
   
var names = ["Doe","Roe"];
var finalQuery;
for (var i =0; i < names.length; i++){
        var q = new Kinvey.Query().equalTo('name',names[i]);
        finalQuery = (finalQuery) ? finalQuery.or(q) : q;
    }
   
var promise = Kinvey.DataStore.find('collection-name', finalQuery);
promise.then(function(response) {
                ...           
    }, function(error) {
      ...
    });
   
   
Also a query like "new Kinvey.Query().equalTo('name','Doe').or()" would fetch all the entities.



Thanks,
Pranav
Kinvey Support

Simply I do not understand how the or() works. It returns the instance of query, yes? Can I do this?


var query = new Kinvey.Query();


for (...) {

query.equalTo('_id', list[i]).or();

}


Is it ok that with the Iast iteration I call the or() method without adding another Query?


 

Daniel,


I'm not entirely certain that I understand your question.  Both of the queries listed would be effective to do what they said they would do and give fairly clear examples on how to use them.  Can you give me an example in which you would need to use a query in a for loop as my answer right now is going to be rather unhelpful without knowing more.


Thanks,

Login or Signup to post a comment