简体   繁体   English

正确的实施搜索方式?

[英]Correct way to implement search?

I'm trying to implement searching books in my meteor app. 我正试图在我的流星应用程序中实现搜索书籍。

So I have this collection called Books , and I need to create a logic to search books by their title. 所以我有这个名为Books集合,我需要创建一个逻辑来按书名搜索书籍。

After a full day reading through the Meteor docs, I implemented the searching logic, but I'm not sure if it's the best way to do it. 经过一整天阅读Meteor文档后,我实现了搜索逻辑,但我不确定这是否是最好的方法。

Here's what I did: 这是我做的:

Server 服务器

Meteor.publish('Books', constraints => {
    // Validate constraints, and generate search query

    return Books.find(<search query>);
});

Client (React component) 客户端(React组件)

Meteor.subscribe('Books', { <search constraints> }, {
        onReady: function () { this.setState({ books: Books.find().fetch() }) }.bind(this)
 });

But I found that Books.find().fetch() in the onReady function returned the previous set of collections appended by the search results (removing duplicates, however), instead of returning just the search results. 但是我发现onReady函数中的Books.find().fetch()返回了搜索结果附加的前一组集合(但是删除了重复项),而不是只返回搜索结果。

This is really unintuitive, as the previous set of collections is not cleared out before populating the results of the new subscribe/publish cycle. 这实际上是不直观的,因为在填充新订阅/发布周期的结果之前不会清除前一组集合。

So, I fixed this by doing executing the search query again at the client: 所以,我通过在客户端再次执行搜索查询来修复此问题:

Meteor.subscribe('Books', { <search constraints> }, {
        onReady: function () { this.setState({ books: Books.find(<search query>).fetch() }) }.bind(this)
 });

But that really doesn't feel right, as I'm executing the search query twice, at both the server and client. 但这确实感觉不对,因为我在服务器和客户端都执行了两次搜索查询。

Is it mandatory to make an additional query at the client's end? 是否必须在客户端进行额外的查询?

If yes, then am I supposed to remove the search logic from the server? 如果是,那么我应该从服务器中删除搜索逻辑吗?

If yes, then what if not all Books are present in the client's Minimongo , while searching at the client's end (say, due to pagination)? 如果是的话,那么如果不是所有的Books都存在于客户的Minimongo中 ,而在客户端搜索(例如,由于分页)?

Is there a more appropriate or "standard" way to implement such an action, or am I misinterpreting the way Meteor's publish/subscribe must be used? 是否有更合适或“标准”的方式来实施此类操作,还是我误解了必须使用Meteor的publish/subscribe方式?

Use a session to store the search constraints and subscribe the books in tracker.autorun which subscribe the books on change of session. 使用会话存储搜索约束并在tracker.autorun中订阅书籍,该书籍订阅会话更改的书籍。

Templae.yourTemplateName.onCreated(function(){
       var self = this;
       self.autorun(function(){
          var searchQuery =Session.get("searchqery"); 
          self.subscribe( 'Books',searchQuery)
       })
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM