超过2个Collection.find

时间:2017-06-10 17:36:38

标签: javascript mongodb angular meteor

我正在使用Angular2和Meteor。我的Chrome控制台中有一个例外(超出最大调用堆栈大小),因为我在客户端添加了该代码:

var userChannelsId = UserChannels.find({idUser: Meteor.userId()});
this.channels = Channels.find({_id: {$in: userChannelsId}});

根据我的发现,当存在无限循环时会发生此异常。我确定错误来自这一行(我调试了我的代码,直到我确定)。 问题来自第二次开始时第一次搜索没有完成的事实吗?

所有功能:

getChannelList(): void {
    console.log('ok');
    var userChannelsId = UserChannels.find({idUser: Meteor.userId()});
    this.channels = Channels.find({_id: {$in: userChannelsId}});
    console.log('ko');

    this.channels.subscribe(channel => {
        this.selectChannel(channel[0]);
    });
} 

编辑:

作为@MichaelSolati我试图只获取userChannel的IdChannel,但我仍然有相同的错误...它返回一个observable而不是一个数组。也许这就是问题所在?这就是我所做的:

getChannelList(): void {
    console.log('ok');
    let userId = Meteor.userId();
    var userChannelsId = UserChannels.find({idUser: userId});
    var values = userChannelsId.map((userChannels:Array<UserChannel>) => {
        let result:Array<String> = [];
        if (userChannels) {
            userChannels.forEach((userChan) => {
                result.push(userChan.idChannel);
            });
        }
        return result;
    });
    this.channels = Channels.find({_id: {$in: values}});
    console.log('ko');
    this.channels.subscribe(channel => { this.selectChannel(channel[0]); });
}

2 个答案:

答案 0 :(得分:1)

由于MeteorRxJS用于查询而更新。虽然它可能并不完美,但它应该会让你走上正确的道路。

private userChannelsSub: Subscription;

getChannelList(): void {
    console.log('ok');
    let userId = Meteor.userId():
    let this.userChannelsSub = UserChannels.find({idUser: userId}).subscribe((userChannels: any[]) => {
        if (Array.isArray(userChannels)) {
            let userChannelsId = userChannels.map((channel: any) => { return channel._id; });
            if (this.channels) { this.channels.unsubscribe(); }
            this.channels = Channels.find({_id: {$in: userChannelsId}}).subscribe((channels: any[]) => {
                this.selectChannel(channels[0]); 
            });
        }
    });
    console.log('ko');
} 

答案 1 :(得分:1)

Alright guys,

I found a solution that works pretty well ! If you have any suggestion to improve my proposition, fill free to comment, I would appreciate it :)

getChannelList(): void {
    let userId = Meteor.userId();
    UserChannels.find({idUser:userId}).subscribe((userChannel:UserChannel[]) =>{
        var channelsId:Array<String> = [];
        userChannel.forEach((userChan)=>{
            channelsId.push(userChan.idChannel);
        });
        this.channels = Channels.find({_id: {$in: channelsId}});
    });
    if(this.channels !== undefined) {
        this.channels.subscribe(channel => {
            this.selectChannel(channel[0]);
        });
    }
}

Thank you all for your answers.