Back to Mikro Orm

@mikro-orm/mongodb

packages/mongodb/README.md

7.0.142.0 KB
Original Source

@mikro-orm/mongodb

MikroORM driver for MongoDB databases, built on top of the official mongodb Node.js driver.

Installation

sh
npm install @mikro-orm/core @mikro-orm/mongodb

Usage

typescript
import { defineEntity, p, MikroORM } from '@mikro-orm/mongodb';

const AuthorSchema = defineEntity({
  name: 'Author',
  properties: {
    id: p.objectId().primary(),
    name: p.string(),
    books: () => p.oneToMany(Book).mappedBy('author'),
  },
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.objectId().primary(),
    title: p.string(),
    author: () => p.manyToOne(Author).inversedBy('books'),
  },
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);

const orm = await MikroORM.init({
  entities: [Author, Book],
  dbName: 'my-db',
  clientUrl: 'mongodb://localhost:27017',
});

const author = orm.em.create(Author, { name: 'Jon Snow' });
orm.em.create(Book, { title: 'My Life on The Wall', author });
await orm.em.flush();

const authors = await orm.em.find(
  Author,
  { name: /Jon/ },
  {
    populate: ['books'],
  },
);

Features

  • Full MongoDB support with native ObjectId handling
  • MongoDB-specific operators$regex, $exists, $elemMatch, and more
  • Automatic serialized primary key conversion (_idid)
  • MongoDB migrations via @mikro-orm/migrations-mongodb
  • Embeddables, virtual entities, and lazy loading

Documentation

See the official MikroORM documentation and the MongoDB usage guide.

License

Copyright © 2018-present Martin Adámek. Licensed under the MIT License.