猫鼬:从2个集合中获取数据

时间:2018-03-13 13:13:32

标签: node.js mongodb api express mongoose

我有2个模型eventsusers,我想让每个事件的用户数量达到类似的目标。

//expected result
[
    {
        "users": 50,
        "eventName": "Event one"
    },
    {
        "users": 46,
        "eventName": "Event two"
    },
    {
        "users": 63,
        "eventName": "Event three"
    }
]

架构是

//events
const eventSchema = new Schema(
    {
        name: String,
        location: String,
        landmark: String,
        dateTime: String,
        status: {type:String, default: 1} //0-finished 1-live
    }
);

//users
const userSchema = new Schema(
    {
        name: String,
        image: String,
        email: {type: String, lowercase: true},
        password: String,
        events: [{type: Schema.Types.ObjectId, ref: 'events'}] //containes ids of events attended
    }
);

我如何使用mongoose或mongoDB查询,下面是我试图解决的方法

usersPerEvent: async (req, res, next) => {

    const events = await Event.find({});
    const users = await User.find({}).count();

    //expected result
    res.status(200).json({
        users: count,
        eventName: eventName
    });
},

期待急需的帮助

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用$lookup,然后使用$unwind& $group计算参加活动的用户数。

这样的东西
User.aggregate([
 {"$lookup":{
   "from":"events", // name of the collection
   "localField":"events",
   "foreignField":"_id",
   "as":"events"
 }},
 {"$unwind":"$events"},
 {"$group":{
     "_id":"$events.name",
     "users":{"$sum":1}
 }},
 {"$project":{
     "_id":0,
     "eventName":"$_id",
     "users":1
 }}
]).exec(function() {...})