복붙노트

[MONGODB] 유성 / 게시 고유의 클라이언트 측 콜렉션에 대한 전략을 구독

MONGODB

유성 / 게시 고유의 클라이언트 측 콜렉션에 대한 전략을 구독

유성 사용하여, 나는이 같은 서버 측 데이터베이스 수집을 공유하는 다른 클라이언트 측 컬렉션을 처리하기 위해 최선의 방법을 궁금하네요. 나는 사용자 컬렉션이, 내 클라이언트 측에 나는 친구가 사용자의 목록을 가지고 있고이 수행하는 전체 사용자 데이터베이스에 쿼리는 일치하는 사용자 이름 목록을 반환하는 검색 기능을 가지고 : 다음 예를 살펴 보겠습니다 질문.

게시 서버 측 방법, 나는 문서의 다른 세트를 리턴 같은 수집에 대한 두 개의 쿼리가 있습니다. 이 데이터는 클라이언트 측에 두 개의 컬렉션으로 가야하나요? 또는 두 쿼리와 일치하는 사용자의 모든 문서가 동일한 모음에서 생을 마감해야합니까? 후자의 경우, 것 I 다음 모두 서버 측과 클라이언트 측 쿼리에 사용되는 중복 코드?

서버에서 :

Meteor.publish('searchResults', function(query){
  var re = new RegExp(query, 'i')
  return Users.find({ 'name' : {$regex: re}})
})

클라이언트의 경우 :

Session.set('searchQuery', null)

Meteor.autosubscribe(function(){
  Meteor.subscribe('searchResults', Session.get('searchQuery'))
})

Template.search.events = {
  'keyup #user-search' : function(e){
    Session.set('searchQuery', e.target.value)
  }
}

_.extend(Template.search, {

  searchResults: function() {
    var re = new RegExp(Session.get('searchQuery'), 'i')
    return Users.find({ 'name' : {$regex: re}})
  }
})

이것은 그럴듯한 해결책처럼 보인다,하지만 최적의 하나. 내가 여러 서버 측 컬렉션에서 검색 결과로 구성되어 새로운 클라이언트 측 콜렉션을 생성하고 싶다면?

해결법

  1. ==============================

    1.공유 영역에서 :

    공유 영역에서 :

    function getSearchUsers(query) {
      var re = new RegExp(query, "i");
      return Users.find({name: {$regex: re}});
    }
    
    function getFriendUsers() {
      return Users.find({friend: true});    // or however you want this to work
    }
    

    서버에서 :

    Meteor.publish("searchUsers", getSearchUsers);
    Meteor.publish("friendUsers", getFriendUsers);
    

    클라이언트의 경우 :

    Template.search.onCreated(function () {
       var self = this;
       self.autorun(function () {
         self.subscribe("searchUsers", Session.get("searchQuery"));
       });
    });
    
    Template.friends.onCreated(function () {
      this.subscribe("friendUsers");
    });
    
    Template.search.helpers({
      searchResults: function () {
        return getSearchUsers(Session.get("searchQuery"));
      }
    });
    
    Template.friends.helpers({
      results: function () {
        return getFriendUsers();
      }
    });
    

    이에서 키 테이크 아웃은 무엇 장면 때 데이터 뒤에 발생한다는 것입니다 와이어를 통해 전송지고하는 것은 명확하지 않다. 유성 결합 나타납니다 서버에 여러 쿼리에서 일치 하였다 기록이를 보내 클라이언트에 이르기까지. 그것은 분할에 다시 같은 쿼리를 실행하는 클라이언트까지 다음의 그들 떨어져.

    예를 들어, 서버 측 컬렉션에서 20 개 레코드가 말한다. 그런 다음이 두 간행 : 제 5 개 매치 기록되는 2 번째 일치 6 똑같다. 유성은 9 개 기록을 보내드립니다. 클라이언트에서, 당신은 그 정확한 실행 같은 쿼리는 서버에서 수행하고 5, 6와 끝까지해야한다 각각 기록합니다.

  2. ==============================

    2.좀 파티에 늦게 비트 해요,하지만 실제로는 하나 개의 서버 집합의 부분 집합에 대한 클라이언트에 별도의 컬렉션을 가질 수있는 방법이있다. 이 예에서 나는 polygonsand 사각형에 대한 정보를 보유하고 실체라는 서버 컬렉션이 있습니다. 공유 코드 (LIB 폴더) :

    좀 파티에 늦게 비트 해요,하지만 실제로는 하나 개의 서버 집합의 부분 집합에 대한 클라이언트에 별도의 컬렉션을 가질 수있는 방법이있다. 이 예에서 나는 polygonsand 사각형에 대한 정보를 보유하고 실체라는 서버 컬렉션이 있습니다. 공유 코드 (LIB 폴더) :

    // main collection (in this example only needed on the server
    Entities = new Meteor.Collection('entities');
    // partial collections
    RectEntities = new Mongo.Collection('rectEntities');
    PolyEntities = new Mongo.Collection('polyEntities');
    

    고객 코드 :

    // this will fill your collections with entries from the Entities collection
    Meteor.subscribe('rectEntities');
    Meteor.subscribe('polyEntities');
    

    구독의 이름이 게시의 이름과 일치해야 함을 기억하라 (그러나 컬렉션의 이름이 아닌 자체) 서버 코드 :

    Meteor.publish('rectEntities', function(){
        Mongo.Collection._publishCursor( Entities.find({shapeType: 'rectangle'}), this, 'rectEntities'); 
        this.ready();
    });
    
    Meteor.publish('polyEntities', function(){
        Mongo.Collection._publishCursor( Entities.find({shapeType: 'polygon'}), this, 'polyEntities'); 
        this.ready();
    });
    

    _publishCursor를 사용하여 훨씬 더 간단 솔루션 user728291 덕분에 ()! _publishCursor () 함수의 세 번째 인수는 새로운 콜렉션의 이름입니다. 출처 : http://docs.meteor.com/#/full/publish_added

  3. ==============================

    3.게시 복합 패키지를 사용

    게시 복합 패키지를 사용

    // main collection
    Entities = new Meteor.Collection('entities');
    
    // partial collections only client side
    RectEntities = new Mongo.Collection('rectEntities');
    PolyEntities = new Mongo.Collection('polyEntities');
    
    // server publish
    Meteor.publishComposite("rectEntities", function(someParameter) {
        return {
                collectionName:'rectEntities',
                find: function() {
                    return Entities.find({shapeType: 'rectangle'});
                },
                children: []
        }
    });
    Meteor.publishComposite("polyEntities", {
            collectionName:'polyEntities',
            find: function() {
                return Entities.find({shapeType: 'polygon'});
            },
            children: []
    });
    

    출처 : http://braindump.io/meteor/2014/09/20/publishing-to-an-alternative-clientside-collection-in-meteor.html

  4. from https://stackoverflow.com/questions/12223866/meteor-publish-subscribe-strategies-for-unique-client-side-collections by cc-by-sa and MIT license