Meteorjs-在后端连接集合的正确方式是什么



我对metro.js非常陌生,并尝试用它构建一个应用程序。这次我想在MEAN堆栈上尝试它,但目前我很难理解如何在服务器端连接两个集合。。。

我想要像mongodb populate这样完全相同的行为来获取内部文档的一些属性。

让我告诉你我的收藏,它有点像

{
  name: 'Name',
  lastName: 'LastName',
  anotherObject: '_id of another object'
}

另一个对象具有一些字段

{
  neededField1: 'asd',
  neededField2: 'zxc',
  notNeededField: 'qwe'
}

因此,每当我调用REST来检索我想要的第一个对象时,它只包含内部对象的neededFields,所以我需要在后端加入它们,但我找不到合适的方法。

到目前为止,在搜索它时,我看到了一些包,这里是列表

  1. Meteor集合帮助程序
  2. 使用关系发布
  3. 反应式加入Meteor(文章)
  4. 加入Meteor.js(文章)
  5. Meteor发布合成

您会发现reywood:publish组合对于"连接"相关集合非常有用,尽管类似SQL的连接在Mongo和Meteor中并不实用。最终得到的是每个集合中相应的文档和字段。

使用myCollectionotherCollection

Meteor.publishComposite('pseudoJoin', {
    find: function() {
        return myCollection.find();
    },
    children: [
        {
            find: function(doc) {
                return otherCollection.find(
                    { _id: post.anotherObject },
                    { fields: { neededField1: 1, neededField2: 1 } });
            }
        }
    ]
});

请注意,otherCollection_id字段将自动包括在内,即使它不在字段列表中。

根据评论更新

由于您只希望将数据返回到REST调用,因此不必担心游标或反应性。

var myArray = myCollection.find().fetch();
var myOtherObject = {};
var joinedArray = myArray.map(function(el){
  myOtherObject = otherCollection.findOne({ _id: el.anotherObject });
  return {
    _id: el._id,
    name: el.name,
    lastName: el.lastName,
    neededField1: myOtherObject.neededField1,
    neededField2: myOtherObject.neededField2
  }
});
console.log(joinedArray); // These should be the droids you're looking for

这是基于1:1的关系。如果有许多相关的对象,则必须按照子对象的数量重复父对象。

最新更新