How to make a publication with the parameters in Meteor and delete the old subscription document?

I want to implement publication with parameters in Meteor, but I am having some problems.

Here is what I have.

How the user enters the keyup event, which subscribes to the publication and passes the input value.

'keyup #customerSearch': function(event, template){ var keyword = template.find('#customerSearch').value; if(keyword){ if(keyword.length >= 3){ Meteor.subscribe('sessioncustomers', keyword); } } } 

The publication uses this keyword to return records.

 Meteor.publish("sessioncustomers", function(keyword){ if(keyword ){ if(keyword.length >= 3){ query.name = new RegExp(regExpQuoted(keyword), 'i' ); Customers.find(query); } else { return null; } }else{ return null; } }); 

Problem. It works and documents are accepted, unless the client changes the keyword or, rather, as the keywords change, the publication publishes additional documents matching the keywords, but the collection of clients never deletes old documents.

How to get old documents that no longer match the customer collection?

I thought that since the subscription options have changed, that inconsistent documents will be unsubscribed and only new relevant documents will be signed.

+6
source share
2 answers

In the keyup you need to “unsubscribe” from the previous publication, otherwise you will save the old documents.

 var sessionCustomersHandler = false; 'keyup #customerSearch': function(event, template) { var keyword = template.find('#customerSearch').value; if (keyword && keyword.length >= 3) var newSessionCustomersHandler = Meteor.subscribe('sessioncustomers', keyword); if (sessionCustomersHandler) sessionCustomersHandler.stop(); sessionCustomersHandler = newSessionCustomersHandler; } 

Also, don't forget to check(keyword, String) in your publish function, for security.

 Meteor.publish("sessioncustomers", function(keyword){ check(keyword, String) if (keyword.length >= 3) return Customers.find({ name: new RegExp(regExpQuoted(keyword), 'i' ) }); }); 
+9
source

Create a local unnamed client collection

 this.SessionCustomers = new Meteor.Collection(null); 

Call the server method to get the desired results. Make a callback clear (delete all) and then paste into this local collection.

 return Meteor.call('sessioncustomers', query, function(err, data) { if (err) { return console.log(err.message); } else { SessionCustomers.remove({}); var item, _i, _len; for (_i = 0, _len = data.length; _i < _len; _i++) { item = array[_i]; SessionCustomers.insert(item); } } }); 
+1
source

Source: https://habr.com/ru/post/955330/


All Articles