'use strict'

let winston = require('winston')
let Rat = require('../api/models/rat')
let Rescue = require('../api/models/rescue')
let mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/fuelrats')

winston.info('Starting firstLimpet fix')

Rescue.find({ firstLimpet: { '$exists': false }, successful: true}).exec().then(function (rescues) {
  winston.info('Found ' + rescues.length + ' rescues with no firstLimpet')
  rescues.forEach(function (rescue) {
    if (rescue.rats.length > 0) {
      Rat.findById(rescue.rats[0]).exec().then(function (rat) {
        if (!rat) {
          winston.info('Rat reference ' + rescue.rats[0] + ' does not exist')
        } else {
          rescue.firstLimpet = rat
          rescue.save(function (err) {
            if (err) {
              winston.error(err)
            } else {
              winston.info('Set rat ' + rescue.rats[0] + ', as firstLimpet')
            }
          })
        }
      })
    } else {
      winston.info('Rescue ' + rescue.id + ' has no rats')
    }
  })
}, function (error) {
  winston.error(error)
})

@@ -1084,8 +1084,838 @@
 ror)%0A%7D)%0A
+%0ARescue.find(%7B rats: %7B '$empty': true %7D, successful: true%7D).exec().then(function (rescues) %7B%0A  winston.info('Found ' + rescues.length + ' rescues with no rats')%0A  rescues.forEach(function (rescue) %7B%0A    if (rescue.firstLimpet) %7B%0A      Rat.findById(rescue.firstLimpet%5B0%5D).exec().then(function (rat) %7B%0A        if (!rat) %7B%0A          winston.info('Rat reference ' + rescue.firstLimpet%5B0%5D + ' does not exist')%0A        %7D else %7B%0A          rescue.rats.push(rat)%0A          rescue.save(function (err) %7B%0A            if (err) %7B%0A              winston.error(err)%0A            %7D else %7B%0A              winston.info('Set rat ' + rescue.firstLimpet%5B0%5D + ', as rat')%0A            %7D%0A          %7D)%0A        %7D%0A      %7D)%0A    %7D else %7B%0A      winston.info('Rescue ' + rescue.id + ' has no firstLimpet')%0A    %7D%0A  %7D)%0A%7D, function (error) %7B%0A  winston.error(error)%0A%7D)%0A

Fix incorrect rats assignment in firsTLimpet script