【发布时间】:2014-06-02 05:04:05
【问题描述】:
好的,这就是我想要做的。我有一个用户模式,它有一个团队键和一个数组作为它的值。例如:
user = {
team : Array
}
数组的值是字符串(团队名称)。我有一个包含团队信息的团队架构,例如名册、状态等。这是我的问题。如果我的用户在数组中有多个团队名称,那么我将如何将所有数据聚合到一个变量中,然后将其传递给我的视图。我以为我可以只使用 for 循环,但视图似乎在聚合完成之前呈现。这是我尝试过的:
// if there is there is more than one team name in the user's team array
if( data[0].teams.length > 1 ){
for(var i = 0; i < data[0].teams.length; i++){
// for each team name in the user array
// find the corresponding team and add that data to the array called team
Team.find( { team : data[0].teams[i] }, function(err, data){
if(err){
throw err;
}
team.push(data);
});
}
// render the view
res.render('coach', {
user: req.user,
fname: self.fname,
lname: self.lname,
email: self.email,
phone: self.phone,
address: self.address,
state: self.state,
teams : [team]
});
}
编辑(添加架构)
用户架构(查看团队数组,找到对应的团队,根据用户架构团队数组中的名称从团队架构返回数据)
var userSchema = new Schema({
username : { type: String, required: true, index: { unique: true } },
fname : { type: String, required: true },
lname : { type: String, required: true },
password : { type: String, required: true },
type : { type: String, required: true },
phone : String,
address : String,
state: String,
conference: String,
email : { type: String, required: true, index: { unique : true } },
teams: Array,
});
团队架构:
var teamsSchema = new Schema({
coach: String,
state: String,
conference: String,
team: String,
roster: [{fname: String, lname: String, number: String}]
});
【问题讨论】:
-
不确定您在这里的实际意思。这实际上是如何在 Mongoose 模式中建模的?和/或您的收藏中文档的基本结构是什么?您可能想要比循环
.find()更简单的方法 -
我试图弄清楚如何根据用户模式的团队数组中的值从另一个模式获取数据。例如.. 在用户模式团队数组中有 ['Bengals', 'Bobcats'] 现在基于这两个字符串我想找到名称为 Bengals 的团队模式和名称为 Bobcats 的团队模式并将它们组合起来返回该数据。
-
我明白这一点,但我是说肯定有比你的做法更好的方法。请编辑您的问题,以包括您从中获取
data的架构以及您正在循环使用.find()的Team模型架构。 -
当然谢谢。我已经添加了架构
标签: node.js mongodb mongoose pug