如何在猫鼬中填充引用另一个模式的对象数组

时间:2019-05-15 18:41:58

标签: node.js mongodb mongoose

你好,我去用Course填充所有作者。

 const courses = await Course.find().populate('author','name -_id');
    console.log(courses);

const Author = mongoose.model('Author',mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    bio:String,
    website:String
}));

const Course = mongoose.model('Course',mongoose.Schema({
    name:String,
    author:[{
        type: mongoose.Schema.Types.ObjectId,
        ref:'Author'
    }]
}));

这就是我得到的:

[ { author: [ [Object], [Object] ],
    _id: 5cdc596bfd5a1e33e4833b2b,
    name: 'nodejs course',
    __v: 1 } ]

但是我去在author数组中填充作者名称 像这样[{author:[{name:'jhon'},{name:'jhon2'}],

[ { author: [ [Object], [Object] ],
    _id: 5cdc596bfd5a1e33e4833b2b,
    name: 'nodejs course',
    __v: 1 } ]

1 个答案:

答案 0 :(得分:0)

我相信这应该对您有用:

const courses = await Course
            .find({})
            .populate('author')
            .exec();

console.log(courses);