【发布时间】:2014-10-10 13:46:00
【问题描述】:
我有一个关于如何使用 MongoDB 和 MeteorJS 获取数组的某个元素的问题。我有以下用户文档架构:
bankList:[
{
id: "34567890987654345678",
name: "xfgchjbkn",
type: "credit"
},
{
id: "09876543456789098767"
name: "65789876t8",
type: "debit"
}
]
我首先只订阅了数组中的部分字段,特别是我收集了所有 id 的列表。然后我有一个编辑屏幕,它应该订阅数组中具有匹配 id 的特定元素的所有字段。我不想只公开单个元素的数组的其余部分。目前,我使用以下方法首先收集一个仅包含 id 的列表:
Meteor.users.find({_id: this.userId},
{fields:{'bankList.id': 1}});
以及下面的发布订阅方法来获取特定元素的信息:
出版:
Meteor.publish("userBankAdvanced", function(bankId){
check(bankId,String);
if(this.userId){
return Meteor.users.find({_id:this.userId,"bankList.id": bankId}, {'bankList.$': 1});
}else{
this.ready();
}
});
订阅:
this.route('edit_account', {
path: '/edit/account/',
waitOn: function(){
if(Session.get("bankId")){
return Meteor.subscribe('userBankAdvanced',Session.get("bankId"));
}
return null;
},
data: function(){
if(Session.get("bankId")){
return Meteor.users.findOne();
}
return null;
},
onBeforeAction: function(){
beforeHooks.isRevise(Session.get("bankId"));
}
});
订阅方法返回包含所有信息的数组的所有元素。 例如,我想要这个(不是包含所有信息的整个列表):
bankList:[
{
id: "34567890987654345678",
name: "xfgchjbkn",
type: "credit"
}]
【问题讨论】:
-
在 $elemmatch 投影上查看 mongo 文档。
-
是的,我使用 $elemMatch 还是 $ 位置索引都没关系。
-
我不明白。您是否在发布函数中使用 $elemMatch 或 $ 并且仍将完整数组发送到客户端?
-
查看字段说明符的流星集合文档。 {字段:{'bankList.$':1}}。
标签: arrays mongodb meteor publish subscribe