title: complex mongoose query with $where
body: <p>Im having a real headache with a mongoose query, I am still quite new to it and wondered if anyone could suggest a solution. </p>
  
  <p>I have the following fields in a gallery collection.</p>
  
  <ul>
  <li><p>status (value of 'public' or 'restricted'), </p></li>
  <li><p>restriction (value of 'canview' or 'cantview'), </p></li>
  <li><p>canview (an array of user ids (ObjectIds) of users permitted to view gallery)</p></li>
  </ul>
  
  <p>I then check fields against the current userID, to see what items are viewable.</p>
  
  <p>how would it be possible to select ALL of the following items</p>
  
  <p>a) all items with 'status' = 'public'</p>
  
  <p>b) all items with 'status' = 'restricted' WHERE 'restricted' = 'canview' AND 'canview' contains the  UserID</p>
  
  <p>I wasnt able to do this using $and and $or, so tried with $where instead. Using the following global function</p>
  
  <pre><code>var existsInArray = function(str,arr) {
      // nb: remember we have typeof ObjectID, so lets convert to strings first!
      var newarr = arr.toString().split(',');
      // now compare..
      if(newarr.inArray(str)) {
        return true;
      }
      return false;
  };
  </code></pre>
  
  <p>I was hoping to do something like this...</p>
  
  <pre><code>exports.listviewable = function(req, res) {
  
      var reqID = req.user.id;
  
      Gallery
          .find()
          .$where(function () {
            return this.status === "public" || ( this.status === "restricted" &amp;&amp; this.restriction === "canview" &amp;&amp; existsInArray(reqID, this.canview));
          })
          .sort('-created')
          .exec(function(err, galleries) {
              if(err) {
                  return res.status(400).send({message:getErrorMessage(err)})
              } else {
                  res.json(galleries);
              }
          }); 
  
  };
  </code></pre>
  
  <p>but this wasnt working  - it appears I wasnt able to use the global existsInArray function in the $where clause ?</p>
  
  <p>Is it possible to do it like this ( similar unresolved question here <a href="https://stackoverflow.com/questions/19605620/how-to-call-external-function-in-mongoose-where-and-passing-this-variable">how to call external function in mongoose $where and passing this variable</a>), or is there a better way to do it with AND and OR ?</p>