---
title: 与 JavaScript 一起使用
sidebar_label: 与原生 JS 一起使用
---

来源：https://mikro-orm.io/docs/usage-with-js

MikroORM 可以通过 `defineEntity` 辅助函数或 `EntitySchema` 与原生 JavaScript 一起使用。两种方式都能提供完整功能，且不需要 TypeScript 或装饰器。

<a id="using-defineentity"></a>
## 使用 `defineEntity`

带属性构建器（`p`）的 `defineEntity` 辅助函数是在 JavaScript 中定义实体的推荐做法：

```js title="./entities/Author.js"
import { defineEntity, p } from '@mikro-orm/core';
import { Book } from './Book.js';

export const Author = defineEntity({
  name: 'Author',
  properties: {
    id: p.integer().primary(),
    name: p.string(),
    email: p.string().unique(),
    age: p.integer().nullable(),
    termsAccepted: p.boolean().default(false),
    born: p.date().nullable(),
    createdAt: p.datetime().onCreate(() => new Date()),
    updatedAt: p.datetime().onCreate(() => new Date()).onUpdate(() => new Date()),
    books: () => p.oneToMany(Book, { mappedBy: 'author' }),
    favouriteBook: () => p.manyToOne(Book).nullable(),
  },
});
```

```js title="./entities/Book.js"
import { defineEntity, p } from '@mikro-orm/core';
import { Author } from './Author.js';
import { BookTag } from './BookTag.js';

export const Book = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    title: p.string(),
    author: () => p.manyToOne(Author),
    tags: () => p.manyToMany(BookTag),
  },
});
```

```js title="./entities/BookTag.js"
import { defineEntity, p } from '@mikro-orm/core';

export const BookTag = defineEntity({
  name: 'BookTag',
  properties: {
    id: p.integer().primary(),
    name: p.string(),
  },
});
```

<a id="using-defineentity-with-a-class"></a>
### 配合类使用 `defineEntity`

你也可以把 `defineEntity` 与类一起使用，而不是只给一个名字。这让你可以用 `new Author()` 创建实例，并在实体上定义自定义方法：

```js title="./entities/Author.js"
import { defineEntity, p } from '@mikro-orm/core';

export class Author {
  id;
  name;
  email;

  getDisplayName() {
    return `${this.name} <${this.email}>`;
  }
}

export const AuthorSchema = defineEntity({
  class: Author,
  properties: {
    id: p.integer().primary(),
    name: p.string(),
    email: p.string().unique(),
  },
});
```

使用类时，实体名会从类名推断出来。之后在使用 ORM 时，类与 schema 两者都可以使用。

<a id="registering-entities"></a>
## 注册实体

在配置中注册实体：

```js
import { MikroORM } from '@mikro-orm/sqlite';
import { Author } from './entities/Author.js';
import { Book } from './entities/Book.js';
import { BookTag } from './entities/BookTag.js';

const orm = await MikroORM.init({
  entities: [Author, Book, BookTag],
  dbName: 'my-db-name',
});
```

<a id="working-with-entities"></a>
## 操作实体

使用 `em.create()` 创建实体实例：

```js
const author = em.create(Author, {
  name: 'Jon Snow',
  email: 'jon@wall.st',
});

const book = em.create(Book, {
  title: 'My Life on the Wall',
  author,
});

await em.flush();
```

<a id="using-entityschema"></a>
## 使用 `EntitySchema`

作为替代方案，你也可以直接使用 `EntitySchema` 以获得更多控制：

```js title="./entities/Author.js"
import { EntitySchema } from '@mikro-orm/core';

export const Author = new EntitySchema({
  name: 'Author',
  properties: {
    id: { type: 'number', primary: true },
    name: { type: 'string' },
    email: { type: 'string', unique: true },
    age: { type: 'number', nullable: true },
    termsAccepted: { type: 'boolean', default: false },
    born: { type: 'Date', nullable: true },
    createdAt: { type: 'Date', onCreate: () => new Date() },
    updatedAt: { type: 'Date', onCreate: () => new Date(), onUpdate: () => new Date() },
    books: { kind: '1:m', entity: () => Book, mappedBy: 'author' },
    favouriteBook: { kind: 'm:1', entity: () => Book, nullable: true },
  },
});
```

关联的 `kind` 参数可以是：

| Value | Relationship |
|-------|-------------|
| `'1:1'` | 一对一 |
| `'m:1'` | 多对一 |
| `'1:m'` | 一对多 |
| `'m:n'` | 多对多 |
| `'embedded'` | 嵌入 |

或者你也可以使用 `ReferenceKind` 枚举，例如 `ReferenceKind.MANY_TO_ONE`。

> 关于 `defineEntity` 的更多内容，请阅读 [`defineEntity` 章节](./61-define-entity.md)。

<a id="example-repository"></a>
## 示例仓库

完整的可运行示例请参见 [Express JavaScript 示例应用](https://github.com/mikro-orm/express-js-example-app)。
