我正在我的网站上投票系统。我有用户模型,用于存储表示用户投票的用户信息(名称,密码,设置等)和投票模型。我应该存储什么以及如何在民意调查模型中创建民意调查,用户只能投票一次?我在下一个架构中结束了:
yesOption: {
username: String,
votes: [String] // Array of voted usernames
},
noOption: {
username: String,
votes: [String],
},
startDate: Date
答案 0 :(得分:1)
//1. User
var UserSchema = new mongoose.Schema({
username: {type: String, lowercase: true},
email: {type: String, lowercase: true}
});
//2. Pool
var PoolSchema = new mongoose.Schema({
rating: {type: Number, default: 0},
votedNumber: {type: Number, default: 0}
});
//3. Voted
var VotedSchema = new mongoose.Schema({
pool: {type: mongoose.Schema.Types.ObjectId, ref: 'Pool'}
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
rank: Number, //rank could be -1 and 1 (-1 is no and 1 is yes) or 0-5
updatedAt: Date
});
如果用户已经为此池投票,您可以更新Voted对象和Pool对象。但通常允许用户投票一次。
此外,要计算Pool的评级,您不必从数据库中选择所有Voted文档。可以在1或2个数据库请求中重新计算它:
if (('undefined' != typeof pool.votedNumber && pool.votedNumber) ||
('undefined' != typeof pool.rating && pool.rating)) {
//Calculate new rating for a pool
var numNewRating = ((pool.rating * pool.votedNumber) + newRank) / (pool.votedNumber + 1);
place.votedNumber += 1;
place.rating = parseFloat(numNewRating);
} else {
//Pool is the first time ranked
place.rating = parseFloat(newRank);
place.votedNumber = 1;
}