Today I witnessed something very strange for me. Lets assume I have file case.graphql:
extend type Query {
getSingleCase(caseId: String): Case
}
type Case {
_id: String!
history: [CaseHistory]
}
type CaseHistory {
_id: String
oldDescription: String
}
So respectfully I have 2 files - CaseModel.ts and CaseHistoryModel.ts:
CaseModel:
import { Schema, model } from "mongoose";
const caseSchema = new Schema({
history: [{ type: Schema.Types.ObjectId, ref: "CaseHistory" }],
});
export default model("Case", caseSchema);
CaseHistoryModel:
import { Schema, model } from "mongoose";
const caseHistory = new Schema({
oldDescription: {
type: String,
}
});
export default model("CaseHistory", caseHistory);
In my caseResolver.ts:
Query:{
getSingleCase: async (
parentValue: any,
args: { caseId: String },
context: any
) => {
return await CaseModel.findById(args.caseId)
.populate({
path: "history",
})
}
}
I try to populate history for the case. But this is returning me:
"MissingSchemaError: Schema hasn't been registered for model "CaseHistory".",
But if I add another query in the resolver:
Query:{
getHistory: async (parentValue: any, args: any, context: any) => {
const casehistory = await CaseHistoryModel.find();
return casehistory;
},
getSingleCase: async (
parentValue: any,
args: { caseId: String },
context: any
) => {
return await CaseModel.findById(args.caseId)
.populate({
path: "history",
})
}
Why is that behaviour? Why I have to add this query called getHistory and even thought I am not using it anywhere, it works with it. Is it because I am engaging usage of CaseHistoryModel and as if I am using it in resolver it is read and correctly applied to schema?