/**
 * Aggregate Queries Adapter Normalization
 */

var _ = require('underscore'),
    async = require('async');

module.exports = {

  // If an optimized createEach exists, use it, otherwise use an asynchronous loop with create()
  createEach: function(valuesList, cb) {
    var self = this;

    // Custom user adapter behavior
    if (this.adapter.createEach) {
      this.adapter.createEach(this.collection, valuesList, cb);
      return;
    }

    // Default behavior
    // WARNING: Not transactional! (unless your data adapter is)
    async.forEachSeries(valuesList, function (values,cb) {
      self.create(self.collection, values, cb);
    }, cb);
  },

  // If an optimized findOrCreateEach exists, use it, otherwise use an asynchronous loop with create()
  findOrCreateEach: function(attributesToCheck, valuesList, cb) {
    var self = this;

    // Clone sensitive data
    attributesToCheck = _.clone(attributesToCheck);
    valuesList = _.clone(valuesList);

    // Custom user adapter behavior
    if (this.adapter.findOrCreateEach) {
      this.adapter.findOrCreateEach(this.collection, attributesToCheck, valuesList, cb);
      return;
    }

    // Build a list of models
    var models = [];

    async.forEachSeries(valuesList, function (values,cb) {
      if (!_.isObject(values)) return cb(new Error('findOrCreateEach: Unexpected value in valuesList.'));

      // Check that each of the criteria keys match:
      // build a criteria query
      var criteria = {};
      _.each(attributesToCheck, function (attrName) {
        criteria[attrName] = values[attrName];
      });

      return self.findOrCreate(criteria, values, function (err, model) {
        // Add model to list
        if (model) models.push(model);
        return cb(err, model);
      });
    }, function (err) {
      // Pass back found/created models
      cb(err,models);
    });
  }

};

@@ -501,16 +501,17 @@
 ctional!
+ 
  (unless
@@ -533,16 +533,39 @@
 ter is)%0A
+    var results = %5B%5D;%0A%0A
     asyn
@@ -601,32 +601,33 @@
 unction (values,
+ 
 cb) %7B%0A      self
@@ -627,16 +627,24 @@
    self.
+adapter.
 create(s
@@ -671,22 +671,195 @@
 es, 
-cb);%0A    %7D, cb
+function(err, row) %7B%0A        if(err) return cb(err);%0A        results.push(row);%0A        cb();%0A      %7D);%0A    %7D, function(err) %7B%0A      if(err) return cb(err);%0A      cb(null, results);%0A    %7D
 );%0A 
@@ -1869,24 +1869,57 @@
 r, model) %7B%0A
+        if(err) return cb(err);%0A%0A
         // A
@@ -1945,17 +1945,16 @@
       if
- 
 (model) 
@@ -1973,24 +1973,25 @@
 model);%0A
+%0A
         
 return c
@@ -1982,29 +1982,23 @@
         
-return cb(err
+cb(null
 , model)
@@ -2043,41 +2043,31 @@
     
-// Pass back found/created models
+if(err) return cb(err);
 %0A   
@@ -2072,20 +2072,22 @@
      cb(
-err,
+null, 
 models);

return proper results from .createEach()