title: mongoose mapreduce()
body: <p>I am keeping track of players' scores in order to record growth. My schema is as follows:</p>
  
  <pre><code>Schema = new schema({
      pid: { type: Number }
    , name: { type: String }
    , alliance: {
        aid: { type: Number }
      , name: { type: String }
      }
    , city_cnt: { type: Number }
    , score: { type: Number }
    , rank: { type: Number }
    , createdTimeAt: { type: Date, default: Date.now }
    , createdDayAt: { type: Number, default: function() { return Math.floor(Date.now() / (24 * 60 * 60)) } }
  })
  </code></pre>
  
  <p>Now I want to pull out one record per day (being the last recorded score for that day) per player. So I have this map reduce:</p>
  
  <pre><code>growthMap = function(){
    emit('createdTimeAt', this.createdTimeAt.toString())
  }
  
  growthReduce = function(prev, doc) { 
    if (doc.createdTimeAt &gt; prev.createdTimeAt) {
      prev.createdTimeAt = doc.createdTimeAt
      prev.score = doc.score
  
      prev.pid = doc.pid
      prev.name = doc.name
    }
  }
  
  mongoose.connect('mongodb://localhost/my_database')
  mongoose.model('Players', Schema)
  
  mongoose.connection.db.executeDbCommand({
    mapreduce: 'players'
  , map: growthMap.toString()
  , reduce: growthReduce.toString()
  , out: 'playerGrowth'
  }, function(err, ret){ 
    if (err) console.log(err)
    else {
      console.log(ret.documents)
      mongoose.connection.db.collection('playerGrowths', function(err, collection){
        collection.find({}).toArray(function(err, docs){
          console.dir(docs)
        })
  
      })
    }
  })
  </code></pre>
  
  <p>The map reduce seems to work fine. The first output <em>console.log(ret.documents)</em> produces this result:</p>
  
  <pre><code>[ { result: 'playerGrowth',
      timeMillis: 11268,
      counts: { input: 14635, emit: 14635, reduce: 15, output: 1 },
      ok: 1 } ]
  </code></pre>
  
  <p>However, whenever I try to query the new collection in the second output <em>console.log(docs)</em>, I get an empty array with no results. I'm sure I am doing something wrong, but the mongoose documentation is lacking when it comes to mapreduce.</p>
  
  <h3>EDIT</h3>
  
  <p>As per Jed's answer below I changed <em>mongoose.connection.db.collection('playerGrowths'</em> to <em>mongoose.connection.db.collection('playerGrowth'</em> and I'm at least getting a result from the find({}).toArray(). However, it's still not what I'm expecting or need...</p>
  
  <p><strong>My new results</strong></p>
  
  <pre><code>[ { result: 'playerGrowth',
      timeMillis: 5743,
      counts: { input: 14635, emit: 14635, reduce: 15, output: 1 },
      ok: 1 } ]
  null
  [ { _id: 'createdTimeAt', value: null } ]
  </code></pre>