猫鼬虚拟与多个foreignFields

时间:2019-02-11 22:35:47

标签: node.js mongoose

我有一个模式Events,其中有一个密钥creator(它是对创建者的引用)和一个密钥musicians,它是与音乐家的组合。

音乐家可以创建Events或作为音乐家参加。我想为音乐家创建一个名为events的虚拟属性,其中将包含音乐家创建的所有事件和参与的事件。

我尝试过:

MusicianSchema.virtual('events', {
    ref: 'Events',
    localField: '_id',
    foreignField: ['creator, musicians'],
    justOne: false,
});

但是这将返回一个空数组。有什么方法可以使它工作,还是猫鼬没有此功能?

编辑

这是事件模式:

const eventSchema = {
    title: {
        type: String,
        trim: true,
        required: true
    },
    description: {
        type: String,
        trim: true
    },
    startDate: {
        type: Number,
        required: true
    },
    endDate: {
        type: Number,
        required: true
    },
    picture: {
        type: String,
        get: getPicture,
    },
    location: {
        type: [Number],
        index: '2dsphere',
        get: getLocation
    },
    creator: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        refPath: 'creatorType'
    },
    musicians: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Musician'
    }],
    creatorType: {
        type: String,
        required: true,
        enum: ['Musician', 'Entity']
    }
};

以及音乐家模式:

const musiciansSchema = {
    name: {
        type: String,
        trim: true,
        required: true
    },
    picture: {
        type: String,
        get: getPicture,
    },
    description: String,
    type: {
        type: String,
        required: true,
        enum: ['Band', 'Artist'],
    },
};

1 个答案:

答案 0 :(得分:2)

具有多个foreignField功能的虚拟猫鼬目前不可用,GitHub上已经请求了新功能的建议,

现在您需要使用单独的虚拟/填充

MusicianSchema.virtual('creatorEvents', {
    ref: 'Events',
    localField: '_id',
    foreignField: 'creator',
    justOne: false,
});

MusicianSchema.virtual('musiciansEvents', {
    ref: 'Events',
    localField: '_id',
    foreignField: 'musicians',
    justOne: false,
});