我正在尝试使用Node,Express和Mongo构建基本的Fantasy Football Web应用程序。我正在使用三个集合-用户,团队和玩家。但是,我对如何将所有模型链接在一起非常着迷。从本质上讲,我希望用户可以单击一个玩家并将其添加到他的特定团队中,然后将其保存在Mongo中以备将来使用。我已经在下面发布了一些代码。任何建议将不胜感激!
当前,我可以通过链接到以下路线的按钮在HTML视图上的列表中显示收藏夹中的玩家:
router.get('/select-player/:id', function(req,res,next){
var playerId = req.params.id;
user = req.user;
// Query to find the selected player
Player.findById(playerId, function (err, player){
if (err) {
// Improve- some type of alert
return res.redirect ('/');
}
// Add to Team Here
// redirect home after selection
res.redirect('/');
});
});
但是,我希望能够将所有选择保存到用户团队中。这将是一组玩家。
团队架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Player = require('./player');
var User = require('./user');
var schema = new Schema({
user: {type: Schema.Types.ObjectId, ref: "User"},
team: [{type: Schema.Types.ObjectId, ref: "Player"}]
});
module.exports = mongoose.model('Team', schema);
玩家模式:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
name: String,
position: String,
teamAbbr: String,
stats:{
"1": Number
},
seasonPts: Number,
seasonProjectedPts: Number,
weekPts: Number,
weekProjectedPts: Number,
});
module.exports = mongoose.model('Player', schema);
或者,我考虑过在User模式中包括一个team字段的想法,该字段将是一组Players,然后删除Team Schema。
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index:true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
});
var User = module.exports = mongoose.model('User', UserSchema);