Mapping Mongoose Models to GraphQL Types
A Mongoose schema and a GraphQL type serve different purposes.
A Mongoose model describes persistence behavior:
const userSchema = new mongoose.Schema({
name: String,
email: String,
createdAt: Date
});
A GraphQL type describes the public API contract:
type User {
id: ID!
name: String!
email: String!
createdAt: DateTime!
}
Do not assume that every Mongoose field should be exposed through GraphQL.
A database may contain internal fields such as:
passwordHash
internalFlags
resetToken
billingProviderId
These should not automatically become GraphQL fields.
Similarly, the GraphQL API may expose computed or aggregated fields that do not exist as individual MongoDB properties.
For example:
type User {
id: ID!
name: String!
postCount: Int!
}
postCount could be computed using an aggregation query without storing it directly in the user document.
This illustrates why GraphQL should be treated as an API abstraction rather than a direct database reflection.
Persistence modelPublic API modelAPI-level representationDatabase documents can contain secrets, internal identifiers, operational metadata, and implementation details. Explicitly decide which information belongs in the public GraphQL schema.
- Mongoose schemas and GraphQL types serve different purposes.
- Not every database field should be public.
- GraphQL can expose computed fields.
- API contracts should not be dictated blindly by persistence models.
Why should a Mongoose document not automatically become a GraphQL response type?