mongoose:填写一个歧视的子文件

我想填充子文档的字段,这是一个常见模式( Notificationable分为MessageFriendRequest )的区分元素。

这个问题与这个问题非常相似: mongoosejs:从两个不同的模式中填充一个objectId数组 ,这是两年前没有解决的。 由于mongoose进化了,鉴别者也是,我再次提出这个问题。

我到目前为止所尝试的:

 Notification.find({_id: 'whatever'}) .populate({ path: 'payload', match: {type: 'Message'}, populate: ['author', 'messageThread'] }) .populate({ path: 'payload', match: {type: 'FriendRequest'}, populate: ['to', 'from'] }) .exec(); 

这是行不通的,因为path是一样的。 所以我试了一下:

 Notification.find({_id: 'whatever'}) .populate({ path: 'payload', populate: [ { path: 'messageThread', match: {type: 'Message'}, }, { path: 'author', match: {type: 'Message'}, }, { path: 'from', match: {type: 'FriendRequest'}, }, { path: 'to', match: {type: 'FriendRequest'}, }, ] }) .exec(); 

哪个也不起作用,也许是因为匹配在子文档中执行,因此没有字段type

有没有解决scheme?


这里是我的(主要)模型,我没有提供用户或MessageThread。

主要文件:

 const NotificationSchema = new Schema({ title: String, payload: { type: Schema.Types.ObjectId, ref: 'Notificationable' }); mongoose.model('Notification', NotificationSchema); 

有效载荷父架构

 let NotificationableSchema = new Schema( {}, {discriminatorKey: 'type', timestamps: true} ); mongoose.model('Notificationable', NotificationableSchema); 

而这两种歧视的可能性:

 let Message = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'User' }, messageThread: { type: Schema.Types.ObjectId, ref: 'MessageThread' } } Notificationable.discriminator('Message', Message); 

和:

 let FriendRequest = new Schema({ from: { type: Schema.Types.ObjectId, ref: 'User' }, to: { type: Schema.Types.ObjectId, ref: 'User' } } Notificationable.discriminator('FriendRequest', FriendRequest);