2012-04-18 17 views
7

Mam następujące schematy:Mongoose - Pobieranie obiektu z ref zapytania

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

Co usiłuję zrobić jest kwerendy zdarzeń, z invitation._id i ostatecznie wrócić użytkownikowi ...

invitees-> eventMember-> user

Do tej pory mam:

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

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

ten wor ks, a konsola pokazuje wyjście myEvent ... (Rozumiem, że nie potrzebuję wypełniania części mojego mongoose zapytania powyżej ... po prostu testuję)

Walczę o to, jak aby uzyskać to, co ja w zasadzie opisać jako: myEvent.invitees.user

EDIT

jako aktualizacja ... Ten działa - jednak to jest do bani, a teraz jestem Będę musiał wykonać kolejną operację db, aby uzyskać użytkownika (zdaję sobie sprawę, że ref w mangurze robi to pod maską)

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 
}); 
+2

w 3.x zamień .run() na .exec() – chovy

Odpowiedz

15

Spróbuj

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

Aktualizacja:

Oto pracuje gist.

Powiązane problemy