2014-03-14 56 views
0

這裏是我的代碼找到了比賽的獲獎者:MongoDB的錯誤沒有文件發現

var date = moment().subtract('days', 1).format("YYYY-MM-DD"); 
console.log(date) 
Contest.findOne({date: date}, function(err, contest){ 
    if(!err){ 
     if(contest){ 
      Participant.find({ questionID : contest._id, random : { $near : [Math.random(), 0] } }).limit(5).exec(function(err, participants){ 
       async.map(participants, function(participant, callback) { 
        contest.winners.push(participant) 
        contest.save(function(err) { 
         callback(err); 
        }) 
       }, function(err) { 
        if (!err) { 
         console.log("Added winners to contest") 
        } else 
         console.log(err) 
       }); 
      }); 
     } 
     else{ 
      console.log("No contest found") 
     } 
    } 
    else{ 
     console.log(err) 
    } 
}) 

模式:

var ContestSchema = new Schema(
{ 
    question:{ 
     type: String, 
     trim: true 
    }, 
    answers:[{ 
     option: {type: String}, 
     correct: {type: Boolean, default : false} 
    }], 
    date: { 
     type: String, 
     trim: true 
    }, 
    priority: { 
     type: Number, 
     trim: true, 
     default : 0 
    }, 
    winners : [{ 
     type: Schema.Types.ObjectId, 
     ref: 'Participant' 
    }] 
}) 

/* 
*Participant Schema 
*/ 

var ParticipantSchema = new Schema(
{ 
    questionID:{ 
     type: String, 
     trim: true 
    }, 
    userID:{ 
     type: String, 
     trim: true 
    }, 
    name:{ 
     type: String, 
     trim: true 
    }, 
    email:{ 
     type: String, 
     trim: true 
    }, 
    mobile:{ 
     type: String, 
     trim: true 
    }, 
    address:{ 
     type: String, 
     trim: true 
    }, 
    landmark:{ 
     type: String, 
     trim: true 
    }, 
    city:{ 
     type: String, 
     trim: true 
    }, 
    state:{ 
     type: String, 
     trim: true 
    }, 
    random:{ 
     type: [Number], 
     default : [Math.random(), 0], 
     index: '2d' 
    } 
}) 

mongoose.model('Contest', ContestSchema) 
mongoose.model('Participant', ParticipantSchema) 

同時節約獲獎者的較量中,這樣可以節省贏家,但我出現錯誤:

{ 
    "status": { 
     "error": 1, 
     "message": { 
      "message": "No matching document found.", 
      "name": "VersionError" 
     } 
    } 
} 

什麼是這個錯誤,我該如何解決這個問題?

回答

1

我會嘗試重寫async.map操作。這將導致一次調用contest.save,你不必擔心任何競爭條件。

async.map(participants, function(participant, callback) { 
    contest.winners.push(participant) 
    callback(); 
}, function(err) { 
    contest.save(function(err) { 
     if (!err) { 
      console.log("Added winners to contest") 
     } else { 
      console.log(err) 
     } 
    }); 
}); 
+0

謝謝Mukesh,它解決了我的問題。 –