猫鼬 - 每次获得计数并选择

时间:2015-04-10 20:08:24

标签: javascript arrays node.js mongodb mongoose

我有两个模式广告:

var AdvertSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true,
        required: 'title cannot be empty'
    },
    advert: {
        type: String,
        default: '',
        required: 'advert cannot be empty'
    },
    sport: [{
        type: Schema.ObjectId,
        ref: 'Sport'
    }],
});
mongoose.model('Advert', AdvertSchema);

和体育:

var SportSchema = new Schema({
    sportName: {
        type: String,
        default: '',
        required: 'sport cannot be empty'
    }
});
mongoose.model('Sport', SportSchema);

我想知道每项运动如何获得广告数量并选择体育模式的_idsportName。请注意,在广告架构中,运动为数组。结果应该是这样的:

[{
    _idOfSport: "some ID",
    sportName: "sport name",
    countOfSportAdverts: "number"
},
etc for other sports...
]

我想我可以使用聚合框架,但我不知道如何。是不是有可能做到这一点?

1 个答案:

答案 0 :(得分:0)

我想这可以解决问题:

Sport.find({}, function(err, sports) {
    var results = [], sportMap = {};

    sports.forEach(function(sport) {
        sportMap["_idOfSport"] = sport._id;
        sportMap["sportName"] = sport.sportName;
        Advert.aggregate([
            {
                $match: {
                    sport: sport._id
                }
            },
            {
                $group: {
                    _id: null,
                    count: { $sum: 1 }
                }
            }
        ], function(err, res){
               sportMap["countOfSportAdverts"] = res[0].count;
               results.push(sportMap);              
        });
    });     
});