Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Retrieving object from ref query

I've got the following schemas:

var userSchema = new Schema({
    firstName: String,
    lastName: String,
    emailAddress: {type: String, set: toLower, index: {unique: true}},
});

var eventMemberSchema = new Schema ({   
    user: { type : Schema.ObjectId, ref : 'User' },
    created: { type: Date, default: Date.now }
});

var eventSchema = new Schema({
    id : String,
    name : String,
    startDate : Date,
    endDate : Date,
    venue : { type : Schema.ObjectId, ref : 'Venue' },

    invitees : [eventMemberSchema],
});

What I'm trying to do, is query the events, with an invitation._id, and ultimately get back the user...

invitees->eventMember->user

So far i've got:

Event
.find({ "invitees._id": req.query.invitation_id })
.populate('user')
.run(function (err, myEvent) {

  console.log('error: ' + err);
  console.log('event:  '+ myEvent);
})

This works, and console shows the output of myEvent... (I realise I don't need the populate part of my mongoose query above for this... i'm just testing)

I'm struggling on how to get, what I'd basically describe as: myEvent.invitees.user

EDIT

As an update... This works - however, it kind of sucks, as now i'll need to do another db operation to get the user (i realise ref in mongoose does this under the hood)

Event
.findOne({ "invitees._id": "4f8eea01e2030fd11700006b"}, ['invitees.user'], function(err, evnt){
    console.log('err:  '+ err);
    console.log('user id:  '+ evnt.invitees[0].user); //this shows the correct user id
});
like image 290
Alex Avatar asked Apr 18 '12 16:04

Alex


1 Answers

Try

Event
.find({ "invitees._id": req.query.invitation_id })
.populate('invitees.user')

Update:

Here is a working gist.

like image 149
aaronheckmann Avatar answered Oct 02 '22 19:10

aaronheckmann