流星 publish-composite 和嵌套 collection

Meteor publish-composite and nested collection

我正在尝试构建一个在 Meteor 中具有多对多关系的应用程序。将有工作、客户和用户 collections。客户可以有多个工作,最重要的是多个用户可以处理同一个工作。

我的 fixtures 文件中的作业 collection 设置如下:

Jobs.insert({
  jobNum: 'Somejob',
  clientId: 'XXXXXXXX',
  clientName: 'Some Client',
  rate: XX,
  userNames: [
    {userId: user1._id},
    {userId: user2._id}
  ],
  active: true
});

我正在根据 publish-composite 的自述文件发布,但我无法让用户发布到客户端。这是发布代码:

Meteor.publishComposite('jobsActive', {
  find: function() {
  // Find all active jobs any client
  return Jobs.find({active: true});
  },

  children: [
    {
     find: function (job) {
        // Return a client associated with the job
        return Clients.find({_id: job.clientId}); 
    }
    },
    {
     find: function (job) {
        // Return all users associated with the job
        // This is where the problem is
        return Meteor.users.find({_id: job.userNames.userId});
     }
   }
 ]
});

我不知道如何正确查找数组。我尝试了很多东西,但没有任何效果。这可能吗?或者我需要用另一种方式来解决这个问题吗?我考虑过在用户 collection 中引用工作,但是工作会比用户多得多,所以这样看起来更有意义。

顺便说一句,我也订阅了 'jobsActive'。另外两个 collection 正在客户端正常运行;我只是无法让用户 collection 发布。

感谢您的帮助和想法。

job.userNames.userId 在您的 collection 中不存在。 job.userNames 是一个 objects 的数组,其键为 userId.

试试 _.map( job.userNames, function( users ){ return users.userId } ).

您的代码将是:

Meteor.publishComposite('jobsActive', {
    find: function() {
        return Jobs.find({active: true});
    },
    children: [
        {
            find: function (job) {
                return Clients.find({_id: job.clientId}); 
            }
        },
        {
            find: function (job) {
                return Meteor.users.find({ _id: { $in: _.map( job.userNames, function( users ) { return users.userId } ) } });
            }
        }
    ]
});

我认为您根本不需要 publish-composite,试试这个代码片段。这个对我有用!

Meteor.publish('jobsActive', function () {
    return Events.find(
    {
        $or: [
            // { public: { $eq: true } },
            { active: true },
            { userNames: this.userId}
        ],
    },
    {
        sort: {createdAt: -1}
    }
    );
});