Example of a class object
{
students: [student._ids will go here],
_id: 61a683115340de04b3eb5448,
teacher: '6170936925956a143a98a02e',
title: '1st Social Studies',
}
is there a way for Mongoose to, in my case, populate the teacher with teacher.firstName, teacher.lastName, and teacher._id as an object when passing it to the front end? This would be a list of objects from a .find if that's significant.
router.route('/').get((req, res, next) => {
classSchema.find((error, data) => {
if (error) {
console.log("bad class")
return next(error)
} else {
console.log(data)
res.json(data)
}
})
})
You can use populate with a projection as the second param:
classSchema.find((error, data) => {
if (error) {
console.log("bad class")
return next(error)
} else {
console.log(data)
res.json(data)
}
}, "students title teacher.firstName teacher.lastName")
or select:
classSchema.find((error, data) => {
if (error) {
console.log("bad class")
return next(error)
} else {
console.log(data)
res.json(data)
}
}).select("students title teacher.firstName teacher.lastName")