I query a Mongo collection called interventions
with Mongoose's findById
method on the Intervention
model. The query returns all fields defined in the associated model.
A student
field also exists in the interventions
collection. Mongoose is not returning it. Presumably, this is because the complex student
object (25-30 key/value pairs) is NOT defined in the Interventions model. I won't ever need to insert documents into the Interventions model.
import mongoose from 'mongoose'
const { Schema } = mongoose
const interventionSchema = new Schema(
{
abs_count_excused: { type: Number },
abs_count_unexcused: { type: Number },
abs_count_total: { type: Number },
student_id: { type: Number, required: true }
}
)
const Intervention = mongoose.model(
'Intervention',
interventionSchema,
'interventions'
)
export default Intervention
Is it possible to retrieve the student
subdocument without defining it in the Interventions model?
Thank you.
CodePudding user response:
I don't believe you can retrieve a value from MongoDB without having it as part of your Mongoose schema in some way. This seems like an opportunity for the Mixed schema type for Mongoose.
Because your concern is translating the complex student
document to a schema and you don't plan on updating it through the Intervention
model, the drawback of the Mixed
schema type doesn't apply. As such, you can add the student
field to your schema like so:
const interventionSchema = new Schema(
{
abs_count_excused: { type: Number },
abs_count_unexcused: { type: Number },
abs_count_total: { type: Number },
student_id: { type: Number, required: true },
student: { type: Object }
}
)