【问题标题】:Meteor: Querying a collection based on a URL parameterMeteor:根据 URL 参数查询集合
【发布时间】:2016-07-21 02:35:43
【问题描述】:

我正在尝试从名为“Babysitters”的架构/集合中显示保姆的独特个人资料(即:保姆用户名、城市、邮政编码等...)。

网址正确包含保姆唯一_id,例如:

http://localhost:3000/test/PqMviBpYAmTA2b5ec

但我无法检索所有其他字段。

meteor question - screenshot

我尝试在两个文件中查询 MongoDB:routes.js 和模板 test.js

1) 在 routes.js 中

Router.route('/test/:_id', {
name: 'test',
data: function () {

return Babysitters.findOne({ _id: this.params._id });
}
});

2) 在 test.js 中

Template.test.helpers({

 data: function () {

 //sitterusername = this.params.sitterusername;
 //console.log(this.params._id );

 return Babysitters.findOne( { _id: this.params._id });
 }
 });

html 文件:test.html

<template name="test"> 
    {{#with data}}
    <ul>
        <li><img src="/" {{photourl}} height="100" width="100" ></li>
        <li>Babysitter username: {{ sitterusername }}</li>
        <li>Presentation: {{ presentation }}</li>
        <li>City: {{ city  }}</li>
        <li>Postal Code: {{ postalcode  }}</li>
        <li>Mother tongue: {{ mothertongue  }}</li>
        <li>Languages spoken {{ languagesspoken }}</li>
        <li>Experience {{ experience }}</li>
        <li>Homework help: {{ homeworkhelpavailable }}</li>
        <li>Hourly wages: {{ hourlywages }} €/h</li>
   </ul>
   {{/with}}
</template>

我尝试了各种方法,但集合字段从未出现在 HTML 文件中。

感谢您的帮助,这里是新手。

K.

【问题讨论】:

  • 你用的是哪个路由器?
  • 如果你写 'console.log(Babysitters.findOne( { _id: this.params._id }));' 会发生什么应用程序运行时在浏览器控制台中?
  • 1) 路由器是铁路由器
  • 2) 当我运行 console.log(Babysitters.findOne( { _id: this.params._id }));在控制台中,我得到: Uncaught TypeError: Cannot read property '_id' of undefined
  • 您必须在路由器中的断点处才能定义this.params._id。该命令在控制台中的任何状态下都不起作用。

标签: meteor meteorite meteor-autoform meteor-helper


【解决方案1】:

您很可能没有将所有Babysitters 发布给客户端,因此您的.findOne() 什么也不返回。

这是一种常见的路由器模式,您希望在其中显示通常不发布的单个文档。在 i-r 中解决此问题的一个好方法是 waitOn 订阅单个文档:

waitOn: function(){
    return Meteor.subscribe('oneBabysitter', this.params._id);
}

在服务器上,发布:

Meteor.publish('oneBabysitter',function(_id){
  return Babysitters.find(_id);
});

请注意,即使此发布仅返回一个文档,您仍然需要执行 .find() 而不是 .findOne(),因为发布需要返回游标或游标数组,而不是对象。

【讨论】:

  • 我已经在 routes.js: Router.route('/test/:_id', { name: 'test', waitOn: function(){ return Meteor.subscribe('oneBabysitter', this.params._id); } }); 和 server\publish.js Meteor.publish('oneBabysitter',function(_id){ return Babysitters.find({ _id: this.params._id })); 中实现了
  • 我不在那里:我被定向到保姆的正确 URL,例如:localhost:3000/test/PqMviBpYAmTA2b5ec>,但显示的是 loading.html 模板而不是 test.html 模板。有什么建议吗?
  • 抱歉,我剪切粘贴了太多次。发布功能显然不知道this.params。尝试更新后的发布。
  • 你好,我已经publish('oneBabysitter',function(this.params._id) 知道为什么我被重定向到加载模板而不是 test.html 模板吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
相关资源
最近更新 更多