以下是我找到比赛获胜者的代码:
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"
}
}
}
这是什么错误,我该如何解决?
答案 0 :(得分: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)
}
});
});