你好,我去用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 } ]
答案 0 :(得分:0)
我相信这应该对您有用:
const courses = await Course
.find({})
.populate('author')
.exec();
console.log(courses);