流星:与加入的关系

时间:2015-01-11 08:01:23

标签: mongodb meteor

我有两个集合Client,WorkClassification。客户端对象可以有多个WorkClassification。所以我的文档结构是

WorkClassification:

{ "classification" : "Web search", "isActive" : true, "_id" : "Htdv9RKrrCbYwPpEt" }
{ "classification" : "Web Tool", "isActive" : true, "_id" : "DS8QAaFnk5XHbcFhH" }
{ "classification" : "Web Work", "isActive" : true, "_id" : "P6kebK7t3BekuHaBP" }

客户:

{ "name" : "Test", "code" : "test", 
   "classifications" : [ 
               { "id" : "DS8QAaFnk5XHbcFhH" }, 
               { "id" : "P6kebK7t3BekuHaBP" }
              ]
}

现在,我希望按每个分类ID显示包含分类详细信息的客户端文档。

助手:

Template.viewClient.helpers({
    client : function() {
        return Client.findOne(Session.get('clientId')); // I have set this value on Router, i can get client values
    },
    classifications: function() {
        var client = Client.findOne(Session.get('clientId'));
        console.log(client.classifications); // I can get Array object here
        return WorkClassification.find({_id : {$in: client.classifications }}); // It does not work
    }
})

日志:

"Exception in template helper: .classifications@http://test:3000/client/views/client/client.js?b6fa170a4dab9684d087c7186827b0c9af0d37aa:185:6
bindDataContext/<@http://localhost:3000/packages/blaze.js?efa68f65e67544b5a05509804bf97e2c91ce75eb:2727:14
Blaze._wrapCatchingExceptions/<@http://localhost:3000/packages/blaze.js?efa68f65e67544b5a05509804bf97e2c91ce75eb:1606:14
Spacebars.call@http://localhost:3000/packages/spacebars.js?3c496d2950151d744a8574297b46d2763a123bdf:169:12
Template.viewClient</<@http://localhost:3000/client/views/client/template.viewClient.js?33c6b442d3e5543e6d54fbf7cfef6f1a55e69a3c:8:12
Blaze.Each/</<@http://localhost:3000/packages/blaze.js?efa68f65e67544b5a05509804bf97e2c91ce75eb:2521:27
viewAutorun/<@http://localhost:3000/packages/blaze.js?efa68f65e67544b5a05509804bf97e2c91ce75eb:1808:14
Blaze._withCurrentView@http://localhost:3000/packages/blaze.js?efa68f65e67544b5a05509804bf97e2c91ce75eb:2043:12
viewAutorun@http://localhost:3000/packages/blaze.js?efa68f65e67544"[…] meteor.js:887
Array [ Object, Object ] client.js:185

我在这方面挣扎了一个星期。

1 个答案:

答案 0 :(得分:1)

您已关闭,但您需要提取所有ID值,而不是{id: value}对。这应该有效:

Template.viewClient.helpers({
  classifications: function() {
    var client = Client.findOne(Session.get('clientId'));

    if(client && client.classifications) {
      var cids = _.pluck(client.classifications, 'id');
      return WorkClassification.find({_id: {$in: cids}});
    }
  }
});

这应该可以解决您的问题,但我认为您以过于复杂的方式存储您的ID(除非您没有显示其他详细信息)。我建议像这样构建你的客户:

{
  name: 'Test',
  code : 'test',
  classifications: ['DS8QAaFnk5XHbcFhH', 'P6kebK7t3BekuHaBP'}]
}

然后您的原始代码就可以使用,您可以像$addToSet$pull这样的简单操作符修改client.classifications