mongodb Mongoose - 在 ObjectId 数组上使用 Populate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10568281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:39:34  来源:igfitidea点击:

Mongoose - using Populate on an array of ObjectId

mongodbmongoose

提问by Alex

I've got a schema that looks a bit like:

我有一个看起来有点像的架构:

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

So my recipients collection, is a collection of object id's referencing my user schema / collection.

所以我的收件人集合是引用我的用户架构/集合的对象 ID 的集合。

I need to populate these on query, so i'm trying this:

我需要在查询时填充这些,所以我正在尝试这个:

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

But obviously 'user' isn't populating...

但显然“用户”并没有出现……

Is there a way I can do this?

有没有办法做到这一点?

回答by Duncan_m

For anyone else coming across this question.. the OP's code has an error in the schema definition.. it should be:

对于遇到此问题的任何其他人.. 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);

回答by aaronheckmann

Use the name of the schema path instead of the collection name:

使用架构路径的名称而不是集合名称:

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