title: Mongoose - REST API - Schema With Query to different model
body: <p>I'm trying to avoid DB Callback Queries.</p>
  
  <p>Assuming that you have two schemas that looks like so : </p>
  
  <blockquote>
    <p>1st) <strong><em>User Schema</em></strong></p>
  </blockquote>
  
  <pre><code> username : {type: String, unique: true},
   age : {type: Number}
  </code></pre>
  
  <blockquote>
    <p>2nd) <strong><em>Activity Schema</em></strong></p>
  </blockquote>
  
  <pre><code> owner: [{type: Schema.Types.ObjectId, ref: 'User'}],
   city: {type: String},
   date: {type: Date}
  </code></pre>
  
  <p>So far so good.</p>
  
  <p>Now lets say you have a route to <code>/user/:id</code>, what you would expect is to get the <code>username</code> and the <code>age</code>, but what if I would also like to return on that route the <strong>latest activity</strong>?</p>
  
  <p><strong>EDIT: Please note that <code>latest activity</code> isn't a value in the database. it's calculated automatically like <code>activity.find({owner: ObjectId(id)}).sort({date: -1}).limit(1)</code></strong></p>
  
  <p>What is done right now:</p>
  
  <pre><code>User.findOne({username:req.params.username}).lean().exec(function(err,userDoc)
  {
  
     if(err) return errHandler(err);
  
     Activity.findOne({owner:userDoc.username}).sort({date:-1}).exec(function(err,EventDoc){
  
       if(err) return errHandler(err);
  
       userDoc.latest_activity = EventDoc._id;
  
       res.json(userDoc);
       res.end();
  
     })
  
  })
  </code></pre>
  
  <p><strong>The problem with the snippet above is that it is hard to maintain, 
  What if we want to add more to this API functionality? We would end in a callback of hell of queries unless we implement Q.</strong></p>
  
  <blockquote>
    <p>We tried to look at Virtual but the issue with that is that you can't
    really query inside a mongoose Virtual, since it returns a
    race-condition, and you are most likely not get that document on time.</p>
  </blockquote>
  
  <p><strong>We also tried to look at populate, but we couldn't make it since the documentation on populate is super poor.</strong></p>
  
  <p><strong>QUESTION:</strong>
  <strong>Is there anyway making this more modular?</strong> </p>
  
  <p><strong>Is there any way avoiding the DB Query Callback of Hell?</strong></p>
  
  <p>For example is this sort of thing possible?</p>
  
  <pre><code>    User.findOne({username:req.params.username}).lean().populate(
  {path:'Event',sort:{Date:-1}, limit(1)}
  ).exec(function(req,res))...
  </code></pre>
  
  <p>Thanks!</p>