title: Mongoose ODM: how to get first one and last five elements from array of embedded documents?
body: <p>I'm writing a simple forum engine with NodeJS/Express/MongoDB and I have a little problem with Mongoose ODM for Mongo.</p>
  
  <p>I have board, thread and post models like those (a little bit simplified):</p>
  
  <pre><code>var boardSchema = mongoose.Schema({
      _id: ObjectId,
  });
  
  
  var threadSchema = mongoose.Schema({
      _id: ObjectId,
      board: {type: ObjectId, ref: 'Board', index: true},
      posts: [postSchema],
  });
  
  
  var postSchema = mongoose.Schema({
      _id: ObjectId,
      thread: {type: ObjectId, ref: 'Thread'},
  });
  </code></pre>
  
  <p>So posts are embedded in thread documents. I want to display a list of threads with some posts: the <strong>first one AND five latest</strong> ones. Is it possible to achieve that in one query? I can get first <strong>OR</strong> latest five using the <strong>slice</strong> function, but I want something more elegant than two almost identical queries. Here is my current query:</p>
  
  <pre><code>threadModel
      .find(
          {board: boardId, is_deleted: false}, 
          {posts: {$slice: -5}}
      )
      .sort({last_updated: 1, is_sticky: 1})
      .skip(settings.threadsOnPage * parseInt(pagePointer, 10))
      .limit(settings.threadsOnPage)
      .populate('board')
      .exec(function(err, threads){
          if (err) return callback(err);
          if (threads === []) return callback(404);
          callback(null, threads);
      });
  </code></pre>