TypeError: course.populate is not a function

Viewed 1565

So i have two 2 Schema namely Course and ct. The code of both the Schema is given below Course Schema

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 Schema

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;

Now when i call the router.get()i am first initializing course variable to Course Schema and the i call course.populate that where i am getting the error .

TypeError: course.populate is not a function i have been at this for hours but cant figure out the problem.i dont know if the code is right or i think i am using the populate function the wrong way.

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());
    }
})
1 Answers

Your problem is due to how you are chaining. Course, not course, has the populate function. Therefore you should chain it like such:

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