我想实现vatting架构,我创建了mongoose架构,如下所示,
我希望按chosen
填充投票和分组,其中选择的是participantId
。
查询贝娄将返回未分组的所有选票。
var ParticipantSchema = new Schema({
firstName: String,
lastName: String
});
var VoteSchema = new Schema({
userId:{type:Schema.ObjectId, ref:'User'},
competitionId:{type:Schema.ObjectId, ref:'Competition'},
chosen:String,
});
var CompetitionSchema = new Schema({
name: String,
type: String,
votes:[{ type: Schema.ObjectId, ref: 'Vote'}],
participants: [ParticipantSchema]
});
var Competition = mongoose.model('Competition', CompetitionSchema);
var Vote = mongoose.model('Vote', VoteSchema);
//query
var name = decodeURIComponent(req.query.name);
var options = [{
$group: {
_id: '$chosen',
count: {$sum: 1}
}
}, {
"$sort": {"count": -1}
}];
Competition.findOne({name: name})
.populate({path: 'votes', select: 'chosen', options: options})
.exec(function (err, result) {
console.log(result)
});
它打印所有未分组的投票
...,
"votes": [
{
"_id": "583d432c7ca0854f9c81a898",
"chosen": "583b0afc0cc87818f02fed2f"
},
{
"_id": "583d6af17e6b7e2b98c01f3b",
"chosen": "583b07da0cc87818f02fed2e" //the same
},
{
"_id": "583d6b147e6b7e2b98c01f3c",
"chosen": "583b07da0cc87818f02fed2e" //the same
}
],
...
任何解决方案或建议。 谢谢