【问题标题】:Meteor: access user's name and profile_picture from the users collection by idMeteor:通过 id 从 users 集合中获取用户名和 profile_picture
【发布时间】:2023-03-02 22:45:01
【问题描述】:

我的项目中有 2 个集合:用户和主题

在主题集合中,我有一个“createdBy”字段,用于存储用户的“_id”。

*Sample object*

{
  "_id": "SNj6C5fqMntSCaXdL",
  "opic": "Best Gaming Laptop",
  "tags": [
    "games",
    "technology",
    "product"
  ],
  "createdBy": "uzsMa4fZgmrrAD9ea",
  "createdAt": "2016-03-06T21:25:38.672Z"
}

在用户集合中,我为每个用户提供了“_id”、“名称”和“profile_picture_url”字段。

{
  "_id": "uzsMa4fZgmrrAD9ea",
  "createdAt": "2016-03-03T03:48:05.787Z",
  "name": "Karan Sarin",
  "profile_picture_url": "https://pbs.twimg.com/pro2_normal.jpg"
}

我正在遍历主题并显示所有主题的列表,并希望显示创建者的个人资料图片和姓名。

{{#each topics}}
  <h2>{{topic_title}}<h2>
  *Profile picture here* *User's name here*
{{/each}}

附:我不想将用户的图片和姓名存储在主题集合中。只是想在需要时从用户的集合中访问它们。

【问题讨论】:

    标签: mongodb meteor meteor-blaze meteor-accounts meteor-helper


    【解决方案1】:

    您可以实现一个帮助函数,该函数返回创建主题的用户的文档。之后,您可以使用#with 表达式将数据上下文设置为与当前主题对应的用户文档。

    例如:

    Template.topicsList.helpers({
        user: function () {
            return Users.findOne({_id: this.createdBy});
        }
    });
    

    <template name="topicsList">
        {{#each topics}}
            <h2>{{topic_title}}<h2>
                {{#with user}}
                    <img src="{{profile_picture_url}}" alt="{{username}}">
                    <strong>{{name}}</strong>
                {{/with}}
        {{/each}}
    </template>
    

    请注意您还订阅了Users集合中的所需文档。

    【讨论】:

      【解决方案2】:

      也许完成您所追求的最简单的方法是将名称作为架构的一部分,在创建主题时将其存储到主题中。然后你可以简单地在你的模板中调用 {{name}}。对于您的个人资料图片,您需要在模板中创建一个自定义变量。 {{getProfileImage userId}} 之类的东西。然后在 common.js 之类的文件中编写一个模板助手,以根据 userId 拉取个人资料图像。

      【讨论】:

      • imageURL 在 users 集合中。你能帮我看看我如何只使用 _id 来获取 URL。我写什么代码?谢谢。
      猜你喜欢
      • 2023-03-16
      • 2019-12-11
      • 2021-03-06
      • 2020-10-09
      • 1970-01-01
      • 2013-07-29
      • 2020-07-13
      • 2012-06-14
      • 1970-01-01
      相关资源
      最近更新 更多