我正在用angularfire写一个应用程序 . 它包括一个node.js服务(在我自己的服务器上运行),它定期对数据做“填充” . 我正在尝试编写.on处理程序来更新父记录中的“计数”字段 . 所以我开始:

guilds = fb.child('guilds')
guilds.on 'child_added', (guildsnap) ->
  console.log 'First read of guild: ' + guildsnap.name()
  guild_applicants = fb.child('applicants').child(guildsnap.name()) 
  guild_applicants.on 'child_changed', (appsnap) ->
    console.log 'Guild Applicant Changed'
    app = new Applicant(appsnap)
    if app.val.rejected then app.reject()
    if app.val.accepted then app.accept()
  guild_applicants.on 'child_removed', (appsnap) ->
    console.log 'Applicant removed, reducing count'
    fb.child('guilds').child(guildsnap.name()).child('applicant_count').transaction (o) -> o - 1
  guild_applicants.startAt().on 'child_added', (appsnap) ->
    console.log 'Applicant added to ' + guildsnap.name() + ', increasing count'
    fb.child('guilds').child(guildsnap.name()).child('applicant_count').transaction (o) -> o + 1

因此,当服务首次加载时,它会为适当的'guild_applicants'集合创建'on'处理程序 . 目的是在添加或删除申请人时,处理程序将相应地更新“applicant_count”字段 .

如果在创建新公会时服务正在运行,则效果很好 . 我可以创建一个公会,添加申请人,删除申请人,并更新applicant_count . 所以,例如,我将有一个有五个申请人的公会,并且applicant_count字段将= 5 .

但是,如果我停止服务并重新启动它,guild_applicant child_added处理程序会立即找到所有这些申请者,并再次增加appliant_count字段 . 所以,例如 . 我最终会有五个申请人,appliant_count字段将= 10 .

从我所看到的,您可以将“startAt”添加到firebase查询中,它将限制响应 . 但我不确定实现它的最佳方法 . 看起来我必须设置一个优先级字段,并使用它?我正在为一个用例编写自定义代码似乎很奇怪,感觉它应该足够常见,成为库的一部分 .

提前感谢任何建议!

EDIT: Trying to use priority...

以不同的方式看待同样的问题;我尝试使用Firebase.ServerValue.TIMESTAMP的优先级,并且它没有像我期望的那样工作......

# on the angularfire client...
# the $set works but the $priority and $save seem to do nothing...?
      $scope.guild.$on 'loaded', (model) ->
        console.log 'guild loaded.'
        if not model
          $scope.guild.$priority = Firebase.ServerValue.TIMESTAMP
          $scope.guild.$save()
          $scope.guild.$set
            initialized: false

# on the node.js server...

# fb is an object that generates me a root firebase reference based on my fb URL
guilds = fb.child('guilds')
# i want this handler to run on every guild, new and existing, when the service starts
guilds.on 'child_added', (guildsnap) ->
  console.log 'First read of guild: ' + guildsnap.name()
  # do stuff that sets up other handlers for guild child events

# i want this handler to run only on guilds that are actually created
# to perform initialization on the guild record
guilds.startAt(Firebase.ServerValue.TIMESTAMP).on 'child_added', (guildsnap) ->
  console.log "New Guild Created"
  guild = new Guild(guildsnap)
  guild.initialize()

所以这里发生的是,'每个公会'.on开火,但是'初始化'.on不会 . 我无法判断优先级是否实际上是由angularFire设置的......?