Meteor, MongoDB get part of array through subscription

家住魔仙堡 提交于 2019-12-01 08:08:18

It looks like you're just missing the "fields" specifier in your "userBankAdvanced" publish function. I wrote a test in meteorpad using your example and it seems to work fine. The bank id is hardcoded for simplicity there.

So instead of

return Meteor.users.find({_id:this.userId,"bankList.id": bankId}, {'bankList.$': 1});

try using

return Meteor.users.find({_id:this.userId,"bankList.id": bankId}, {fields: {'bankList.$': 1}});

No luck, in meteor the "fields" option works only one level deep. In other words there's no builtin way to include/exclude subdocument fields.

But not all is lost. You can always do it manually

Meteor.publish("userBankAdvanced", function (bankId) {
  var self = this;
  var handle = Meteor.users.find({
    _id: self.userId, "bankList.id": bankId
  }).observeChanges({
    added: function (id, fields) {
      self.added("users", id, filter(fields, bankId));
    },
    changed: function (id, fields) {
      self.changed("users", id, filter(fields, bankId));
    },
    removed: function (id) {
      self.removed("users", id);
    },
  });
  self.ready();
  self.onStop(function () {
    handle.stop();
  });
});

function filter(fields, bankId) {
  if (_.has(fields, 'bankList') {
    fields.bankList = _.filter(fields.bankList, function (bank) {
      return bank.id === bankId;
    });
  }
  return fields;
}

EDIT I updated the above code to match the question requirements. It turns out though that the Carlos answer is correct as well and it's of course much more simple, so I recommend using that one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!