Meteor,基于从另一个集合检索到的ID查询集合



我有两个集合。

ItemList = new Mongo.Collection('items');
BorrowerDetails = new Mongo.Collection('borrow');
ItemList.insert({
brand: "brand-Name",
type: "brand-Type",
._id: id
});
BorrowerDetails.insert({
key: "ItemList.id", //equals to .id of the ItemList Collection
name : "borrowerName"
});

问题
如何根据ItemList集合中的特定类型从BorrowerDetails集合中检索记录。

前任。从BorrowerDetails集合检索所有记录,其中key等于ItemList集合上类型等于"Desktop"的记录的id。

return BorrowerDetails.find(
{ key : 
ItemList.find(
{ type : 'Desktop' },
{ fields: {'_id':1 } }
)
}
); //error!  

注意,我的笔记本电脑中现在没有nodejs,所以可能会有几个错误,因为我无法测试它。

首先,创建一个发布文件(例如server\publications\boroPub.js)。在该文件中,您应该创建一个公布方法。这里的逻辑很简单,首先获取itemid数组,然后将其作为参数在Mongo-select$in中传递。

Meteor.publish('queryBorrowerTypeDesktop', function(criteria)
{
var itemArr = ItemList.find( { type : 'Desktop' },
{ fields: {'_id':1 } });
if(itemArr){
//itemArr found, so do a select in using the array of item  id we retrieved earlier
var borrowers = BorrowerDetails.find({ key: { $in: itemArr } });
return borrowers;
}else{
//found nothing- so return nothing
return [] 
}
});

第二,在路由器中:

Router.route('/test', {
name: 'test',
action: function()
{
//change accordingly.
},
waitOn: function()
{//subscribe from publisher that we just created...
return [
Meteor.subscribe('queryBorrowerTypeDesktop') 
];
},
data: function() {
if(Meteor.userId())
{
// also include the sorting and limit so your page will not crash. change accordingly. 
return {
borrowerDetails: BorrowerDetails.find({},{sort: {name: -1},        limit: 30}),
}
}
}
});

请注意,在数据中,BorrowerDetails.find()不需要进行任何过滤,因为它在订阅过程中已经过过滤,并已缓存在浏览器的MiniMongo中。

最新更新