Paperbag Writer
Paperbag Writer

Reputation: 823

Proper way to findOne document in Template Event?

I am trying to findOne document in my Template.admin.events code. I have a form and onClick I want to verify if the ID of the ObjectID entered is an existing document in my collection and fetch that result to show it on the template.

My event code on the client :

Template.admin.events({
    'click #btnAjouterObjet'(event) {
            let objetIdInput = $('#object_id').val().toString();
            Meteor.subscribe('objetsFindOne', objetIdInput, {
                onReady: function () {
                    let obj = Objets.findOne();
                    if (obj) {
                        console.log("found");
                        console.log(obj);
                        objetsArr.push(objetIdInput);
                    }
                    else {
                        console.log("not found");
                        console.log(obj);
                    }
                }
            });
        }
});

In my Objets api :

Meteor.publish('objetsFindOne', function objetsFindOne(param_id){
    return Objets.find({_id : param_id});
  })

I have verified and my objetIdInput always change on click when a different Id is entered but the subscribe always returns the first id entered. I also added the onReady because otherwise it returned undefined.

I am new to Meteor and I have also tried to subscribe to all the collection and doing the find on the client but I don't think it is the best idea as my collection has about 22000 documents.

Upvotes: 0

Views: 54

Answers (3)

Paperbag Writer
Paperbag Writer

Reputation: 823

I opted for the use of a method :

Client side:

'click #btnAjouterObjet'(event) {
        let objetIdInput = $('#object_id').val().toString();
        let result = Meteor.call('findObj', objetIdInput, function (error, result) {
            if (error) {
                console.log(error.reason);
                return;
            }
            console.log(result);
        });
    }

On the server side :

 Meteor.methods({
findObj: function (param_id) {
      console.log(Objets.find({ _id: param_id }).fetch());
      return Objets.find({ _id: param_id }).fetch();
    },
});

Upvotes: 0

Jeremy S.
Jeremy S.

Reputation: 4659

Just to elaborate a little bit on the first answer, as to how to change this pattern:

(1) you should place your Meteor.subscribe() call in your Template.admin.onCreated() function.

(2) the subscription reads from a reactive value, for example, new ReactiveVar().

(3) now, anytime the reactive value changes, the subscription will re-run. So, in your template event, you set the reactive value to the id and let the subscription handle the rest.

Discover Meteor and other resources should be helpful on any details.

Upvotes: 2

Derrick Gremillion
Derrick Gremillion

Reputation: 268

You are going about this all wrong. I suggest you take a look at Template-Level Subscriptions

Upvotes: 0

Related Questions