Search code examples
javascriptmeteorclient-servermeteor-accounts

How to add custom user data to meteor accounts


I'm trying to build out a system so that the default accounts sytem built into MeteorJS will have a friends list. Unfortunately, this just isn't working, and I can't figure out why. I'm currently attempting to simply add a friendList array to the user.profile, and then simply append the added user to the end of that list. Here's the code: Server:

 Meteor.methods({
      addFriend: function(friendUsername){
          friendUserId = Meteor.users.findOne({username:friendUsername});
           if(friendUserId){
               Meteor.users.update({_id:Meteor.userId()}, {$set:{"profile.friendList":Meteor.user().profile['friendList'].push(friendUserId)}});
              return 1;
          }
          else return 0;
      }
  });

Client:

Template.addFriendPage.events({
    "keypress .addFriendByUsername": function(event, template){
        if(event.which == 13){
            event.preventDefault();

            var user = Meteor.userId();
            var friendUsername = template.find(".addFriendByUsername").value;
            console.log(friendUsername);
            console.log(user);
            console.log(Meteor.call("addFriend",friendUsername));
            if(Meteor.call("addFriend", friendUsername)){
                alert("successfully added friend!");
                template.find(".addFriendByUsername").value = "";   

            } else alert("not a valid username");
        }
    }
  });

The html is just a template that I can put a username into. And I know I have to add in the part where I add the current user to the other user's friend list, but I want to get this working first.


Solution

  • Your main problem is you're setting a push. Instead, you need to use $push.

    var userId = Meteor.user();
    Meteor.users.update(userId, {$push:'profile.friendList':friendUserId});
    

    Second, I'd consider it a moderately bad idea to store friends on the user profile. Consider creating a friends collection.