2012-05-12 43 views
23

陣列上使用填充我有一個模式,它看起來有點像:貓鼬 - 的ObjectId

var conversationSchema = new Schema({ 
    created: { type: Date, default: Date.now }, 
    updated: { type: Date, default: Date.now }, 
    recipients: { type: [Schema.ObjectId], ref: 'User' }, 
    messages: [ conversationMessageSchema ] 
}); 

所以我的收件人的集合,是的對象ID的引用我的用戶模式/集合的集合。

我需要填充這些上查詢,所以我想這一點:

Conversation.findOne({ _id: myConversationId}) 
.populate('user') 
.run(function(err, conversation){ 
    //do stuff 
}); 

但很明顯,「用戶」不填充...

有沒有一種方法,我可以做到這一點?

回答

25

使用的模式路徑,而不是集合名稱的名稱:

Conversation.findOne({ _id: myConversationId}) 
.populate('recipients') // <== 
.exec(function(err, conversation){ 
    //do stuff 
}); 
+1

這不是爲我工作:( – SomethingOn

62

對於任何人碰到這個問題來了..在OP的代碼已經在模式定義的錯誤..它應該是:

var conversationSchema = new Schema({ 
    created: { type: Date, default: Date.now }, 
    updated: { type: Date, default: Date.now }, 
    recipients: [{ type: Schema.ObjectId, ref: 'User' }], 
    messages: [ conversationMessageSchema ] 
}); 
mongoose.model('Conversation', conversationSchema); 
+2

你先生剛剛救了我痛苦的世界。*提示帽子* –

+0

好辦法!但你怎麼能做到唯一對象ID的數組?由於沒有重複? – Gura

+0

{type:Schema.ObjectId,ref:'User',unique:true} –