Skip to content

REST API on MongoDB

A deep dive into the api-typeorm-mongo starter: MongoRepository access, ObjectId identifiers, documenting a type that has no JSON Schema equivalent, and what changes when the schema is not owned by migrations.

5 min read Source

Source: api-typeorm-mongo

This starter is the Postgres one with the persistence layer swapped. Reading both side by side is useful precisely because so little changes: the module graph, the async provider, the controller and the OpenAPI wiring are identical, while the repository type, the identifier type and the migration story differ.

That contrast tells you which parts of the design belong to the framework and which to TypeORM.

Project layout

src
├─ app.controller.ts                        # GET /, GET /users, POST /users
├─ app.module.ts                            # root module: imports MongoModule
├─ bootstrap.ts                             # pipeServer + pipeSwagger
├─ ormconfig.json                           # mongodb connection
├─ swagger.spec.ts                          # asserts the document, no database
└─ modules/data-store
   ├─ mongo.module.ts                       # exports UserService
   ├─ entity/user.entity.ts                 # @ObjectIdColumn + @ApiProperty
   ├─ services/user.service.ts              # MongoRepository
   └─ configs/mongo-data-source.service.ts  # async DataSource provider

The module graph

@Module({
  providers: [MongoDataSource, UserService],
  exports: [UserService]
})
export class MongoModule {
}

Note the difference from the Postgres starter: only UserService is exported, not the data source. Nothing outside the feature module needs the connection — the controller asks the service, the service asks the data source. Export only what other modules actually consume.

The connection provider

@Injectable()
export class MongoDataSource {

  @CreateProvider({
    provide: DataSource,
    useFactory: async () => {
      return await new DataSource(<DataSourceOptions>{
        ...pgConfig,
        logging: process.env.NODE_ENV !== "prod"
      }).initialize();
    },
    providers: []
  }) private dataSource: DataSource;

  getEntityManager(): MongoEntityManager {
    return this.dataSource.mongoManager;
  }

  getMongoRepository<T>(entity: EntityTarget<T>): MongoRepository<T> {
    return this.dataSource.getMongoRepository(entity);
  }
}

Structurally this is the same pattern as the relational starter: an async factory, awaited by the injector, wrapped in a class that exposes a narrow API. Two things are Mongo-specific:

  • The factory has no dependencies (providers: []) because there is no query logger to inject.
  • Access goes through mongoManager and getMongoRepository(). A MongoRepository is not a Repository: it lacks SQL-specific operations such as query builder joins, and exposes find, findOne, save, delete and aggregation instead.
@Injectable()
export class UserService {

  @Inject() mongoDataSource: MongoDataSource;

  async find(): Promise<Array<User>> {
    return this.getRepository().find();
  }

  protected getRepository(): MongoRepository<User> {
    return this.mongoDataSource.getMongoRepository(User);
  }
}

protected getRepository() keeps the repository construction in one place, so a future change — soft deletes, a different database name per tenant — touches a single method rather than every call site.

The identifier problem

This is the one genuinely new concept, and it affects both the entity and the documentation:

@Entity()
@ApiSchema({name: "User"})
export class User {

  @ObjectIdColumn()
  @ApiProperty({
    type: String,
    description: "Mongo ObjectId serialized as a 24 character hex string",
    example: "65a4f0c2b1e4f6a3d8c9e123",
    readOnly: true
  })
  id: ObjectId;

  @Column()
  @ApiProperty({example: "Igor"})
  firstName: string;
}
  • @ObjectIdColumn() marks the property as the Mongo primary key. TypeORM generates the ObjectId on insert.
  • On the wire, an ObjectId serialises to a 24-character hex string, so clients see "65a4f0c2b1e4f6a3d8c9e123" rather than an object.
  • @ApiProperty({type: String}) is required. Without an explicit type, resty-swagger would treat the ObjectId class as a model, register it as a component and emit a meaningless object schema. Declaring String plus readOnly and an example keeps the document truthful.

Unresolvable types become bogus components

Any class used as a decorated property type is registered as a components.schemas entry. For types that have no JSON Schema equivalent — ObjectId, Buffer, driver-specific values — always pass the serialised form with type: String. The same rule applies to GraphQL: see Code-first GraphQL for the Float! case.

Routes

Method Path Handler Notes
GET / getHello plain text
GET /users getUsers returns an array of users
POST /users createUser saves a new document, returns it with its id
@POST("users")
@ApiOperation({summary: "Create a user", operationId: "createUser"})
@ApiResponse({status: 200, type: User})
createUser() {
  const user = new User();
  user.age = 100;
  user.firstName = "Igor";
  user.lastName = "Surname";
  return this.userService.save(user);
}

A real round trip against a local mongo container:

POST /users → {"age":100,"firstName":"Igor","lastName":"Surname","id":"6b13373aa3f8b6b32769ffe0"}
GET  /users → [{"id":"6b13373aa3f8b6b32769ffe0","firstName":"Igor","lastName":"Surname","age":100}]

No migrations

ormconfig.json sets synchronize: false and there is no migration directory, because MongoDB is schema-less: TypeORM creates the collection on first write and columns simply appear. Two consequences follow:

  • There is nothing to run before the app boots, so the starter works against an empty database.
  • Indexes and validators are not covered by this starter. In a real application you would add them explicitly (queryRunner.createIndex, createCollection with a validator) or manage them outside the application, since synchronize would only create indexes declared on the entity.
cd resty-starters
docker compose up -d --wait mongo   # mongo on 27017, database typeix, no auth
cd api-typeorm-mongo
npm install && npm run start

Tests

File Kind What it proves
src/app.controller.spec.ts unit controller behaviour with a stubbed service
src/swagger.spec.ts build-time routes and the User component, including the ObjectId mapping
test/app.e2e-spec.ts in-process GET / through the real router

The swagger spec asserts exactly the detail that is easy to get wrong:

expect(user.properties.id).toEqual(expect.objectContaining({
  type: "string",
  readOnly: true
}));

If someone removes the type: String from @ApiProperty, this test fails instead of the document quietly gaining an ObjectId schema.

Pitfalls

  • @ObjectIdColumn() is required, not @PrimaryGeneratedColumn(). The relational decorator emits an integer sequence column, which Mongo cannot honour.
  • The entity glob still points at dist/, so npm run start:prod needs a build first.
  • find() without a filter loads the whole collection. Fine for a starter; in a real application add pagination at the service boundary so controllers do not grow query parameters one by one.
  • ObjectId in responses is a string, but ObjectId in requests would have to be converted. This starter has no route that accepts an id, which is why no conversion code exists.

Next: Code-first GraphQL moves from REST to a schema built out of decorators.