   updatedWithValue: (id, value) =>
     # Do nothing. Code should not be updating generated field by itself anyway.
 
+  @updateAll: ->
+    setupObservers true
+
 class globals.Document extends globals.Document
   @_sourceFieldUpdated: (id, name, value, field) ->
     # TODO: Should we check if field still exists but just value is undefined, so that it is the same as null? Or can this happen only when removing the field?

          $set:
            _schema: '1.0.0'

setupObservers = ->
  setupTargetObservers = (fields) ->
    for name, field of fields
      # There are no arrays anymore here, just objects (for subdocuments) or fields
      if field instanceof globals.Document._ObservingField
        field.setupTargetObservers()
      else if field not instanceof globals.Document._Field
        setupTargetObservers field

  for document in globals.Document.list
    setupTargetObservers document.Meta.fields
    document.setupSourceObservers()

setupMigrations = ->
  for document in globals.Document.list

      Log.error "PeerDB exception: #{ e }: #{ util.inspect args, depth: 10 }"

class globals.Document._TargetedFieldsObservingField extends globals.Document._TargetedFieldsObservingField
  setupTargetObservers: (updateAll) =>
    initializing = true

    referenceFields = fieldsToProjection @fields
    handle = @targetCollection.find({}, fields: referenceFields).observeChanges
      added: catchErrors (id, fields) =>
        @updateSource id, fields if updateAll or not initializing

      changed: catchErrors (id, fields) =>
        @updateSource id, fields

      removed: catchErrors (id) =>
        @removeSource id

    if updateAll
      handle.stop()
      return

    initializing = false

# Have to refresh with new methods from TargetedFieldsObservingField
_.extend globals.Document._ReferenceField.prototype,
