简体   繁体   中英

Meteor return value from array to use it in another collection

This question is almost the same as my previous one: Meteor return value as string , but I still haven't figuered it all out.

My situation: I got a collection users and a collection Projects . In my Projects collection, I got a document 'Invited' with an array of invited users (their user ID's). Like this:

{
"_id" : "XpS6CLJpujtTKEdBe",
"projectname" : "Projectnaam 1",
"invited" : [
    "vcHkGjTMQG57tTPRG",
    "zhwaQTSRSA9RM3Phr",
    "3JxXtYmbqAMEBezti"
]
}

I want to return the Firstname and Surname of the invited users. But the firstname en surname collection are in the users collection. So I got to get the ID's from the Array, and use each ID to get the Firstname en Surname of the users collection. Can anyone help me to achieve this? Thank you!

Yours, L

Loop through each project, find the relevant user document by searching the users collection for each id in the document's invited array, and return the modified projects array documents using map() :

Template.projects.helpers({
    projects: function(){        
        return Project.find({}).map(function (doc){
            doc.invited = User.find({"_id": {"$in": doc.invited}}, {fields: {"firstname": true, "surname": true}});
            return doc;
        });         
    }
});

<template name="projects">
    {{#each projects}}
        <h1>{{this.projectname}}</h1>
        <ol>
        {{#each this.invited}}
            <li>{{firstname}}  {{lastname}}</li>
        {{/each}}
        </ol>
    {{/each}}
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM