简体   繁体   中英

EJS: How can I render two or more populated colletions from mongoose in EJS file

I've a issue related to render in EJS two or more populated collections from mongoDB.

In order to pass a most rich context of my "problem", I'll share with you guys some of my code here: models, routes and views.

Model Schema

var mongoose = require("mongoose");

var playerSchema = mongoose.Schema({
    namePlayer:         String,
    email:              String,
    playerTeam: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref:  "Team"
        },
        nameTeam: String
    }
});

var coachSchema = mongoose.Schema({
        nameCoach:  String,
        email:      String,
        nameTeams: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Team"
        }   
    ]
});

var teamSchema = mongoose.Schema({
    nameTeam: String,
    teamPlayers: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Player"
        }
    ],
    teamCoaches: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Coach"
        }       
    ]   
});

module.exports = mongoose.model("Player", playerSchema);
module.exports = mongoose.model("Coach", coachSchema);
module.exports = mongoose.model("Team", teamSchema);

Router Schema

var express = require("express");
var passport = require("passport");
var router  = express.Router();
var Player = require("../models/player");
var Team = require("../models/team");
var Coach = require("../models/coach");

// Find Team by ID
router.get("/resultTeam", function (req, res, next) {

    var teamId = req.query.team;

    Team.findById(teamId).populate("teamPlayers").populate("teamCoaches").exec(function(err, currentTeam) {   
        if(err){
           console.log(err);
        } else {
           console.log(currentTeam);
           res.render("./player/resultTeam", {teams: currentTeam });
        }
    });
});

console.log(currentTeam)

{ teamPlayers: 
   [ { equipe: [Object],
       _id: 5b20023443589331491e0903,
       namePlayer: 'Zico',
       email: 'lorem@ipsum.com',
       __v: 0 },
     { equipe: [Object],
       _id: 5b215e6460adc33528d29f06,
       namePlayer: 'Pelé',
       email: 'lorem@ipsum.com',
       __v: 0 } ],
  teamCoaches: 
   [ { equipes: [Object],
       _id: 5b1f063b999c3c285aa9f3e7,
       nameCoach: 'Harrison Ford',
       email: 'lorem@ipsum.com',
       __v: 1 } },
  _id: 5b1f061c91b4a7284b6d4945,
  nameTeam: 'Real Madrid',
  __v: 1 }

Having pasted all my code and expected output here, what I'm trying to achieve now is exhibit in my frontend (ejs file) some basic information about my "team":

View File

<thead>
    <tr>
        <th><i class="fa fa-image"></i></th>
        <th><i class="fa fa-star"></i> Athlete</th>
        <th class="hidden-phone"><i class="fa fa-question-circle"></i> Coach</th>
        <th><i class="fa fa-bookmark"></i> Email</th>
        <th></th>
    </tr>
</thead>
<tbody>

    <% teams.teamplayers.forEach(function(player) { %>    
    <tr>
        <td></td>
        <td><a href="basic_table.html#"><%= player.namePlayer %></a></td>
        <td class="hidden-phone"><%= coach.coachName %></td>
        <td><%= player.email %></td>
          <td>
            <form style="display: inline" action="/player/<%= player._id %>" method="GET">
               <button class="btn btn-default btn-xs"><i class="fa fa-search-plus"></i></button>
            </form>
        </td>
    </tr>   
    <% }); %>
</tbody>

With this last code (ejs view) everything is working properly, until I add this line:

<td class="hidden-phone"><%= coach.coachName %></td>

Obviously this is wrong, bu I've no idea how can I populate "Coaches Name" for every single athlete or team without to put a second forEach statment, which is not gonna work as well.

By the way, I readed a lot about this issue and I couldn't find the best approach to solve it... looks like async function is a possibility here, but honestly, I'm not sure.

Probably the solution is easier than I think, but after 13 hours I'm not capable to figure this out by myself.

coach object does not exist. You do have teamCoaches however, which is an array. Not sure if there ever can be more than one coach, if you should adjust your logic to loop through teamCoaches the same way you loop through teamPlayers .

If it is always one coach below code should work:

<td class="hidden-phone"><%= teamCoaches[0].nameCoach %></td>

Your object there is currentTeam and that's where you should get the object properties from like this:

    <tbody>

    <% currentTeam.teamplayers.forEach(function(player) { %>    
    <tr>
        <td></td>
        <td><a href="basic_table.html#"><%= player.namePlayer %></a></td>
        <td class="hidden-phone"><%= coach.coachName %></td>
        <td><%= player.email %></td>
          <td>
            <form style="display: inline" action="/player/<%= player._id %>" method="GET">
               <button class="btn btn-default btn-xs"><i class="fa fa-search-plus"></i></button>
            </form>
        </td>
    </tr>   
    <% }); %>
</tbody>

on the this line <td class="hidden-phone"><%= coach.coachName %></td> please edit it like so: <td class="hidden-phone"><%= player.coachName %></td>

that should be just fine then

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