2016-09-05 3 views
0

내 사이트에서 투표 시스템을 만들고 있습니다. 나는 사용자 사용자 정보 (이름, 암호, 설정 등) 및 사용자 설문을 나타내는 Poll 모델을 저장하는 모델을 가지고 있습니다. 사용자가 한 번만 투표 할 수있는 설문 조사를 만들려면 설문 조사 모델을 저장하고 어떻게해야합니까? 나는 다음 스키마에서 종료 :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; 
}