Meteor, MongoDB get part of array through subscription

后端 未结 2 384
花落未央
花落未央 2021-01-14 03:54

I have a question about how to just get a certain element of an array using MongoDB and MeteorJS. I have the following schema for the user document:

    bank         


        
相关标签:
2条回答
  • 2021-01-14 04:08

    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}});
    
    0 讨论(0)
  • 2021-01-14 04:20

    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.

    0 讨论(0)
提交回复
热议问题