我最近发现了nodejs + mongodb(通过mongoosejs)。 我正在为我的覆盆子编写一个小应用程序,在一个大型的led面板上显示一个记分牌。
我实际上有2个问题
为我需要的匹配配置记分板:
2支球队:每队有n名球员(1比......) 时间限制 目标限制 每个球队得分的目标
这是我的模型文件:
var MatchSchema = new Schema({
teams: [{ type: Schema.Types.ObjectId, ref: 'Team' }],
goals_left: Number,
goals_right: Number,
time_limit: Number,
goal_limit: Number
});
var TeamSchema = new Schema({
name: {
type: String,
required: [true, "Team Name is required"],
},
players: [{ type: Schema.Types.ObjectId, ref: 'Player' }]
});
var PlayerSchema = new Schema({
name: {
type: String,
required: [true, "Player Name is required"],
}
});
问题1:
创建团队:在我的Teams集合中插入一个玩家对象数组(我使用复选框选择团队中的玩家)没有问题。
创建匹配:我无法在我的匹配集合中插入2个团队对象的数组,这里是表单和控制器操作:
表格
div.row.form-group
each i in [0,1]
div.col
label(for='teams-'+i) #{ i===0 ? 'Left' : 'Right' } Team
select.form-control(type='select' id='teams-'+i placeholder='Select TEAM'+i name='teams['+i+']' required='false' data-target='/team/new')
option(value=null) Select #{ i===0 ? 'Left' : 'Right' } Team
for team in all_teams
option(value=team._id) #{team.name}
创建匹配代码:
// Handle Match create on POST.
exports.match_create_post = [
(req, res, next) => {
if(!(req.body.teams instanceof Array)){
if(typeof req.body.teams==='undefined') {
req.body.teams=[];
}else{
match_teams=new Array(req.body.teams);
}
}
next();
},
(req, res, next) => {
const errors = validationResult(req);
// Create a team object with escaped and trimmed data.
var match = new Match(
{
//teams: [ "5a92f691d5038fd56c648664", "5a92fa14b4d7f5d665da9ef4"],
teams: match_teams,
time_limit: req.body.time_limit,
goal_limit: req.body.goal_limit,
status: req.body.status
}
);
if (!errors.isEmpty()) {
res.render('match_form', { title: 'Create Match', match: match, errors: errors.array()});
return;
} else {
match.save(function (err) {
if (err) { return next(err); }
res.redirect(match.url);
});
}
}
];
奇怪的是,我为创建一个团队做了同样的事情,它完全可以工作...... 我无法理解为什么req.body.teams未定义
问题2:
如果我在我的团队字段中手动插入2个团队,例如: 球队:[“5a92f691d5038fd56c648664”,“5a92fa14b4d7f5d665da9ef4”]
当我想显示比赛详情时:
控制器查询:
exports.match_detail = function(req, res, next) {
var id = mongoose.Types.ObjectId(req.params.id);
async.parallel({
match: function(callback) {
Match.findById(id)
.populate('teams')
.populate('teams.players')
.exec(callback);
},
}, function(err, results) {
if (err) { return next(err); }
if (results.match==null) {
var err = new Error('Match not found');
err.status = 404;
return next(err);
}
// Successful, so render
res.render('match', {
title: 'match Detail',
match: results.match
} );
});
};
团队名称已正确显示,但对于玩家详细信息,我只能访问_id,而不是名称
任何帮助将不胜感激: - )
谢谢
克莱门特