Writing in collection in Meteor

时间:2015-05-04 19:34:05

标签: meteor

I'm building a friend list managing system with meteor. For that, I send a notification to a user who receive a request. Then, when I accept it, I want to edit this user profile to change the status of the request in the user profile.

  Template.navigation.events({
    'click #ok-btn': function(e, tmpl){
      Meteor.users.update({_id: Meteor.userId()}, {
        $set: {
          'profile.friends': [...]
      }});
      Meteor.call('removeNotif', Meteor.user()._id, this.id);
   });

The friend object array of the profile is built like this :

[{id: foo, status: bar}, [...]]

How do I update the status here ? I can not simply do

var friendList = Meteor.user().profile.friends,
          i = 0;
      for(i = 0; i < friendList.length; i++)
        if(friendList.id == id)
          break;

      Meteor.users.update({_id: Meteor.userId()}, {
        $set: {
          'profile.friends'+[i]+'.satus': myNewStatus
      }});

How must I proceed ?

2 个答案:

答案 0 :(得分:1)

You could just edit the friends list beforehand and pass the updated one to your update method:

var friendList = Meteor.user().profile.friends,
          i = 0;
      for(i = 0; i < friendList.length; i++) {
        if(friendList[i].id == id) {
          friendList[i].status = myNewStatus;
          break;
        }
      }
      Meteor.users.update({_id: Meteor.userId()}, {
        $set: {
          'profile.friends': friendList
      }});

Or, using the positional $ operator:

Meteor.users.update({_id: Meteor.userId(), 'profile.friends.id': id}, {
  $set: {
    'profile.friends.$.status': myNewStatus
  }
});

答案 1 :(得分:1)

使用MongoDB positional operator $

Meteor.users.update({_id: Meteor.userId()}, {
    $set: {
        'profile.friends.$.status': myNewStatus
    }
});