bp123
bp123

Reputation: 3417

Search an array for a specific value

I'm trying to search an array to find this._id. studentId returns the correct Id however fav returns Object {_id: "fMNS3M5dW356C46Sq", emails: Array[1], profile: Object, roles: Array[2]}

How do I get var fav to return the studentId in the array or return null if the id isn't found?

Path: list.js

Template.list.events({
'click .favourite':function(event,template) {
      console.log('click');
        var studentId = this._id;
        var fav = Meteor.users.findOne({"profile.favorites":  studentId });

      console.log(fav);

        if (candidateId === fav) {
          Meteor.users.update({_id: Meteor.userId()}, {$pull:{"profile.favorites":studentId}});
        } else {
          Meteor.users.update({_id: Meteor.userId()}, {$push:{"profile.favorites":studentId}});
        };
    }
});

Upvotes: 1

Views: 41

Answers (1)

Stephen Woods
Stephen Woods

Reputation: 4049

Based on your comment, I think you want:

Template.list.events({
  'click .favourite':function(event,template) {
    console.log('click');
    var studentId = this._id;
    var fav = null;

    if( Meteor.users.findOne({"profile.favorites":  studentId }) ) {
      fav = studentId;
    }
    if (candidateId === fav) {
      Meteor.users.update({_id: Meteor.userId()}, {$pull:{"profile.favorites":studentId}});
    } else {
      Meteor.users.update({_id: Meteor.userId()}, {$push:{"profile.favorites":studentId}});
    };
  }
});

This will set fav to be the studentId if Meteor.users.findOne returns with something.

Upvotes: 1

Related Questions