使用refPath的Mongoose填充ObjectID的数组返回空数组

时间:2019-12-03 11:32:03

标签: node.js mongodb mongoose

issue.js

const mongoose;
const schema = new mongoose.Schema({
    docs: {
        type: [mongoose.Schema.Types.ObjectId],
        refPath: 'coll',
        required: true
    },
    coll: {
        type: String,
        required: true,
        enum: ['Product', 'Service']
    }
});

module.exports = mongoose.model('Issue', schema);

部分index.js

try{
    let issues = await Issue.find().populate('docs');

    console.log(issues);
    //every issue in issues, has an empty 'docs' array, when it should consist of products/services that exist

}catch(e){}

不确定数组为什么不能使它工作,我尝试将docs字段设置为奇异的ObjectId,并且效果很好。我唯一能想到的是,因为它是一个数组,所以refPath必须不同,但是我不确定我可以添加什么,因为我尝试使用'this.coll'。

1 个答案:

答案 0 :(得分:0)

我看到您的架构中有一个错误。不知道这是否是问题,但是您可以尝试。

const mongoose;
const schema = new mongoose.Schema({
    docs: [{
        type: mongoose.Schema.Types.ObjectId, // <-- This line
        refPath: 'coll',
        required: true
    }],
    coll: {
        type: String,
        required: true,
        enum: ['Product', 'Service']
    }
});