在字符串中传递_id和搜索查询

Passing an _id and a search query in the string

本文关键字:id 搜索 查询 字符串      更新时间:2023-09-26

meteor 用于测试项目。无法弄清楚在使用他们拥有的示例todo应用时如何传递 ID 和搜索参数。

目前,我的铁路由器中有:

this.route('team', {
     path: '/team/:_id',
     onBeforeAction: function() {
         this.todosHandle = Meteor.subscribe('todos', this.params._id);
         // Then filter mongoDB to search for the text
 }});

问题是,我还想传递一个可选的search参数来搜索todos。所以像path: '/team/:_id(/search/:search)?'

任何想法如何做到这一点?

从您的解释来看,听起来您希望仔细控制哪些文档实际发布到客户端,而不是发布所有文档并缩小客户端上的结果集。在这种情况下,我建议首先在服务器上定义一个发布,如下所示:

Meteor.publish('todosByTeamIdAndSearch', function(todoTeamId, searchParameter) {
    var todosCursor = null;
    // Check for teamId and searchParameter existence and set
    // todosCursor accordingly. If neither exist, return an empty
    // cursor, while returning a subset of documents depending on
    // parameter existence.
    todosCursor = Todos.find({teamId: todoTeamId, ...}); // pass parameters accordingly
    return todosCursor;
});

要了解有关定义更精细发布的更多信息,请查看此内容。

使用上面定义的发布,您可以像这样设置路由:

Router.route('/team/:_id/search/:search', {
    name: 'team',
    waitOn: function() {
        return Meteor.subscribe('todosByTeamIdAndSearch', this.params._id, this.params.search);
    },
    data: function() {
        if(this.ready()) {
            // Access your Todos collection like you normally would
            var todos = Todos.find({});
        }
    }
});

从示例路由定义中可以看出,您可以完全按照您希望直接在调用 Router.route() 函数时看到的路径来定义路由的路径,并访问直接传入的参数,就像在 waitOn route 选项中一样。由于发布的定义与我建议的相同,因此您只需将这些路由参数直接传递给Meteor.subscribe()函数即可。然后,在"data路由"选项中,检查订阅是否已准备就绪后,可以像往常一样访问Todos集合,而无需进一步缩小结果集(如果不需要这样做)。

要了解有关如何配置路由的更多信息,请查看以下两个链接:铁路由器路由参数和铁路由器路由选项

在客户端上,您只需在顶级代码中使用Meteor.subscribe('todos');'todos'这里不是指集合,它是一个任意字符串。订阅不关心你走的路线。

在服务器上,您将有一个如下所示的发布函数:

Meteor.publish('todos', function() {
    if (!Meteor.userId()) return;
    // return all todos (you could pass whatever query params)
    return Todos({});
});

然后,在路由定义中:

Router.route('team', {
    path: '/team/:_id',
    data: function() {
        if (this.params.query) { //if there's a query string
             return Todos.find(/* according to the query string */).fetch();
        else {
             // return all the user's todos
             return Todos.find({ uid: this.params._id }).fetch();
        }
    }
});