TypeError:course.populate不是函数



所以我有两个2模式,即Course和ct。下面给出了这两个模式的代码课程架构

const validator=require('validator');
let Schema=new mongoose.Schema({
coursename:{
type:String,
unique:true,
required:true,
validate(value){
if(!validator.isAlphanumeric(value))
throw new Error("Enter a valid course name");
}
}
})
Schema.virtual('ct',{
ref:'Ct',
localField:'_id',
foreignField:'courseid'
});
Schema.virtual('finalpaper',{
ref:'Finalpaper',
localField:'_id',
foreignField:'courseid'
})
let Course=mongoose.model('Course',Schema);
module.exports=Course;

Ct架构

const mongoose=require('mongoose');
let Schema=new mongoose.Schema({
file:{
type:Buffer,
required:true
},
filename:{
type:String,
required:true
},
courseid:{
type:mongoose.Schema.Types.ObjectId,
ref:'Course'
}
},{
timestamps:true
})
let Ct=mongoose.model('Ct',Schema);
module.exports=Ct;

现在,当我调用router.get((时,我首先将课程变量初始化为course Schema,然后我调用course.populate来填充我得到错误的地方。

TypeError:course.populate不是函数我已经研究了好几个小时了,但还是弄不出问题。我不知道代码是否正确,或者我认为我使用populate函数的方式不对。

userRouter.js

router.get('/course/:course/ct',async(req,res)=>{
var match={};
var sort={}
if(req.query.sortBy){
part=req.query.sortBy.slice(':');
sort[part[0]]=part[1]==='desc'?-1:1
}
try{
let course=await Course.find({coursename:req.params.course});
await course.populate({
path:'ct',
match,
options:{
limit:req.query.limit,
skip:req.query.skip,
sort
}
}).execPopulate();
course.ct.forEach(Deletefile);
res.send(course.ct);
}catch(e){
console.log(e);
res.status(500).send(e.toString());
}
})

您的问题是由于如何进行链接造成的。具有填充功能的是Course,而不是course。因此,你应该这样链:

let course=await Course.findOne({coursename:req.params.course}).populate({
path:'ct',
match,
options:{
limit:req.query.limit,
skip:req.query.skip,
sort
}
}).execPopulate();

最新更新