2012-04-18 6 views
7

ho i seguenti schemi:Mongoose - Recupero oggetto dalla domanda rif

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

Quello che sto cercando di fare, è interrogare gli eventi, con un'invitation._id, e, infine, tornare l'utente ...

invitees-> eventMember-> utente

Finora ho:

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

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

Questo wor ks e console mostra l'output di myEvent ... (Mi rendo conto che non ho bisogno della parte popolamento della mia query mangusta sopra per questo ... sto solo testando)

Sto lottando su come per ottenere, quello che io descrivo come fondamentalmente: myEvent.invitees.user

EDIT

come un aggiornamento ... Questa funziona - tuttavia, che tipo di schifo, come ora i' Ho bisogno di fare un'altra operazione db per ottenere l'utente (mi rendo conto che ref in mangusta lo fa sotto il cofano)

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

in 3.x sostituire .run() con .exec() – chovy

risposta

15

Prova

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

Aggiornamento:

Ecco un gist lavoro.

Problemi correlati