[英]how to add more fields(in mongoose schema) into a field(which is an array of objects) and these objects are reference to another mongoose schema?
[英]how to populate array of objects in mongoose that reference to another schema
你好,我去給所有作者加課程。
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:[{name:'jhon'},{name:'jhon2'}],
在author數組中填充作者姓名[{author:[{name:'jhon'},{name:'jhon2'}],
[ { author: [ [Object], [Object] ],
_id: 5cdc596bfd5a1e33e4833b2b,
name: 'nodejs course',
__v: 1 } ]
我相信這應該為您工作:
const courses = await Course
.find({})
.populate('author')
.exec();
console.log(courses);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.