[英]how to populate array of objects in mongoose that reference to another schema
hello i went to populate all author with 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'
}]
}));
this is what i get: 这就是我得到的:
[ { author: [ [Object], [Object] ],
_id: 5cdc596bfd5a1e33e4833b2b,
name: 'nodejs course',
__v: 1 } ]
but i went to populate author name inside the author array like this [{author:[{name:'jhon'},{name:'jhon2'}],
但是我像这样
[{author:[{name:'jhon'},{name:'jhon2'}],
在author数组中填充作者姓名[{author:[{name:'jhon'},{name:'jhon2'}],
[ { author: [ [Object], [Object] ],
_id: 5cdc596bfd5a1e33e4833b2b,
name: 'nodejs course',
__v: 1 } ]
I believe this should work for you: 我相信这应该为您工作:
const courses = await Course
.find({})
.populate('author')
.exec();
console.log(courses);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.