Search code examples
mongodbtitaniumcloudtitanium-mobile

Query Event : Check whether a particular item present in an object array


In my application I'm querying to events. I've to select the events that meets the following requirements.

1. Value of user_id should not be equal to the current user's id

2. The custom field 'cancelled' should be false

3. The custom field 'participants' should contain current user's id

In which cancelled property will have a boolean value and participants is an array that contains some objects.

participants array:

participants : [{"userID":"52a15bebf172080g3g02abcd","nickname":"Anand"},{"userID":"58t85eryjc2fx3489nx4m90d","nickname":"Midhun"}];

I have written the following for getting the events

function getUsers(user){
    Cloud.Events.query({
    per_page: 1000,
    where : {
        "cancelled" : false,
        "user_id":{"$ne":user.id},
        //TODO: here I need to get the participants whose userID is equal to user.id
        }
    }, function(e){
        if (e.success) {
            alert('Success:\n' + 'Count: ' + e.events.length);
        } else {
            alert('Error:\n' +
                ((e.error && e.message) || JSON.stringify(e)));
        }
    });
}

How can I check whether user.id is present in the participants object array?

UPDATE

I tried the following

where : {
    "cancelled" : false,
    "participants.userID" : user.id,
    "user_id":{"$ne":user.id},
}

but returns 0. It should return 1.


Solution

  • After a lot of research I found the answer. I changed the where clause as follows

    where : {
        "cancelled" : false,
        "participants" :{ "$elemMatch" : { "userID" : user.id }}
        "user_id":{"$ne":user.id},
    }
    

    Complete code as follows

    function getUsers(user){
        Cloud.Events.query({
           per_page: 1000,
           where : {
              "cancelled" : false,
              "participants" :{ "$elemMatch" : { "userID" : user.id }}
              "user_id":{"$ne":user.id},
           }
        }, function(e){
            if (e.success) {
                alert('Success:\n' + 'Count: ' + e.events.length);
            } else {
                alert('Error:\n' +
                    ((e.error && e.message) || JSON.stringify(e)));
            }
        });
    }
    

    This link helped me to resolve the issue.