2012-05-12 48 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} –