title: Mongoose how to sort array of objects returned from query
body: <p>I have the following schema:</p>
  
  <pre><code>const userSchema = new Schema({
    local: {
      email: {type: String, unique: true, sparse: true, lowercase: true, trim: true, required: true},
      password: {type: String, required: true},
    },
    username: {type: String, unique: true, lowercase: true, trim: true},
    Items: [{
      name: {type: String, trim: true},
      createdAt: {type: Date, default: Date.now}
    }]
  });
  </code></pre>
  
  <p>And I'm using the following query to retrieve all of the items:</p>
  
  <pre><code>User.findById(req.user.id, 'Items -_id', (err, user) =&gt; { ... });
  </code></pre>
  
  <p>which returns the following:</p>
  
  <pre><code>{ Items: 
     [ 
       { name: 'test1',
         _id: 58c70800a03d09a31bb7fc17,
         createdAt: Mon Mar 13 2017 20:58:40 GMT+0000 (GMT) },
       { name: 'test2',
         _id: 58c70826a03d09a31bb7fc18,
         createdAt: Mon Mar 13 2017 20:59:18 GMT+0000 (GMT) } 
     ] 
  }
  </code></pre>
  
  <p><strong>My question is:</strong> How can I edit my mongoose query to return objects inside <code>Items</code> array sorted in descending order based on <code>createdAt</code> property? i.e. so that <code>test2</code> appears above <code>test1</code>. </p>
  
  <p>(some additional info, the items array on average will be of length 3-10 per user and i'm using Nodejs as the backend, for this reason, would sorting the array on the app side be bearable because of its small size or too inefficient due to Nodejs single threaded nature?), Thanks.</p>