Mr Robot
Mr Robot

Reputation: 897

Mongoose: Getting data from 2 collections

I have 2 models events and users, i want to get number of users attended each event something like.

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

The Schema are

//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
    }
);

how do i query using mongoose or mongoDB, below is the method i'm trying somethig out

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
    });
},

Looking forward for much needed help

Thank you

Upvotes: 1

Views: 52

Answers (1)

s7vr
s7vr

Reputation: 75924

You can use $lookup followed by $unwind & $group to count the no of users who attended event.

Something like

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() {...})

Upvotes: 2

Related Questions