我想在子文档使用动态引用的子文档数组中填充ObjectId。即我有一个引用创建者的模型“ Comment”,模型类型为“ User”或“ Artist”:
const CommentSchema = new Schema({
id: ObjectId,
by: {
type: ObjectId,
refPath: 'byModel',
required: true
},
byModel: {
type: String,
required: true,
enum: ['User', 'Artist'],
default: 'User'
},
...
},
);
当我Comment.model.find({}).populate('by')
进行操作时,我得到的填充字段包含一个User或Artist实体,如预期的那样。
但是现在我有一个“ Tape”模型,其中包含注释数组:
const TapeSchema = new Schema(
{
title: {type: String, required: true, max: 500,unique: true},
artist: { type: ObjectId, ref: 'Artist'},
comments: [{type: ObjectId, ref: 'Comment'}],
...
}
});
现在我要填充tape.comments.by
:
const tape = await Tape.model.findById(req.params.id).populate(['comments', 'comments.by', 'tracks', 'artist'])
if(!tape)
... //do some exception handling
res.status(200).send(tape)
这不起作用。返回了我的磁带,根据需要填充了注释,byModel
存在,并且相应地包含'User'/'Artist',但是comments.by
只是一个ObjectId,没有填充。
我已经尝试不加选择地明确选择.select(['comments.by, comments.byModel'])
。