38

次のようなスキーマがあります。

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

しかし、明らかに「ユーザー」は入力されていません...

これを行う方法はありますか?

4

2 に答える 2

118

この質問に出くわした他の人のために..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);
于 2012-11-06T03:20:29.827 に答える
38

コレクション名の代わりにスキーマ パスの名前を使用します。

Conversation.findOne({ _id: myConversationId})
.populate('recipients') // <==
.exec(function(err, conversation){
    //do stuff
});
于 2012-05-14T21:33:37.970 に答える