2016-09-05 13 views
0

私は自分のサイトで投票システムを作ります。私はユーザーユーザーの情報を(名前、パスワード、設定など)とポールモデルを格納するモデルを持っています。私は何を保存すべきですか、世論調査を作成する投票モデルでは、ユーザーは一度だけ投票できますか?私は次のスキーマに終わった:MongoDBで投票システムを整理する

yesOption: { 
    username: String, 
    votes: [String] // Array of voted usernames 
}, 
noOption: { 
    username: String, 
    votes: [String], 
}, 
startDate: Date 

答えて

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 
}); 

ユーザーはこのプールのためにすでに投票した場合は、投票対象とプールのオブジェクトを更新することができます。しかし、通常、ユーザーは一度投票することができます。

また、プールの評価を計算するには、データベースからすべての投票文書を選択する必要はありません。データベースへの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; 
} 
関連する問題