【问题标题】:Publish fields of Meteor.user to the client将 Meteor.user 的字段发布到客户端
【发布时间】:2014-07-19 22:28:25
【问题描述】:

我正在尝试将自定义余额字段添加到meteor.user 集合,但我在从客户端访问它时遇到问题。

如果我使用自动发布和不安全创建一个新项目,则事件将不起作用。假设我要发布用户集合的 createdAt 字段:

# server
if Meteor.isServer
 Meteor.publish "userData", ->
  console.log @userId
  if @userId
    Meteor.users.find
      _id: @userId
    ,
      fields:
        createdAt: 1

  else
    @ready()
  return

# client

if Meteor.isClient 
 Meteor.subscribe "userData"

/project/collections/user.coffee

无论如何,当我在浏览器的控制台中键入 Meteor.user() 时,我仍然无法读取 createdAt 字段。我做错了什么?

【问题讨论】:

    标签: coffeescript meteor


    【解决方案1】:

    在成功的情况下,您的函数需要在客户端返回一个游标。显式的return 阻止了这一点。我会这样写:

    Meteor.publish 'userData', ->
      return @ready() unless @userId
      Meteor.users.find @userId, fields: createdAt: 1
    

    【讨论】:

    • 我在你之前几秒钟错误地解决了它。非常感谢您向我解释了我做错了什么(正确)。无论如何我都按照官方指南并将其转换为咖啡,为什么它不起作用?是官方文档的错误还是咖啡的翻译?
    • 这是一个翻译问题,因为 CoffeeScript 确实返回的方式。如果你在 find 前面加上一个明确的返回值,比如:return Meteor.users.find...,那么它可能会起作用。在您的代码中,它不会返回那里,而是到达最后并仅将 undefined 返回给调用者。在 CoffeeScript 中,您通常不希望在函数末尾显式地 return
    • 对不起,大卫,你为什么要返回 @ready 函数而不是调用它?这只是一个错字吗?
    猜你喜欢
    • 2021-05-28
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多