Ent*_*ore 7 mongoose mongodb node.js discriminator mongoose-populate
我想填充一个子文档的字段,这是一个普通Schema中的已区分元素(区Notificationable
分为Message
或FriendRequest
)。
这个问题与这个问题非常相似:mongoosejs:从不同的模式填充一个objectId的数组,两年前没有解决。由于猫鼬的进化和歧视性的发展,我再次提出这个问题。
到目前为止我尝试过的是:
Notification.find({_id: 'whatever'})
.populate({
path: 'payload',
match: {type: 'Message'},
populate: ['author', 'messageThread']
})
.populate({
path: 'payload',
match: {type: 'FriendRequest'},
populate: ['to', 'from']
})
.exec();
Run Code Online (Sandbox Code Playgroud)
这是行不通的,因为路径相同。所以我尝试了:
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();
Run Code Online (Sandbox Code Playgroud)
这也不起作用,可能是因为匹配是在子文档中执行的,因此没有field type
。
有什么解决办法吗?
这是我的(主要)模型,我没有提供User或MessageThread。
主要文件:
const NotificationSchema = new Schema({
title: String,
payload: {
type: Schema.Types.ObjectId,
ref: 'Notificationable'
});
mongoose.model('Notification', NotificationSchema);
Run Code Online (Sandbox Code Playgroud)
有效负载父架构
let NotificationableSchema = new Schema(
{},
{discriminatorKey: 'type', timestamps: true}
);
mongoose.model('Notificationable', NotificationableSchema);
Run Code Online (Sandbox Code Playgroud)
以及两种区分的可能性:
let Message = new Schema({
author: {
type: Schema.Types.ObjectId,
ref: 'User'
},
messageThread: {
type: Schema.Types.ObjectId,
ref: 'MessageThread'
}
}
Notificationable.discriminator('Message', Message);
Run Code Online (Sandbox Code Playgroud)
和:
let FriendRequest = new Schema({
from: {
type: Schema.Types.ObjectId,
ref: 'User'
},
to: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}
Notificationable.discriminator('FriendRequest', FriendRequest);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
418 次 |
最近记录: |