与 JavaScript 一起使用
只需使用 EntitySchema
即可获得具有清除身份映射的新副本。
¥Since MikroORM 3.2, we can use EntitySchema
helper to define own entities without decorators, which works also for Vanilla JavaScript.
在 本节 中阅读有关
EntitySchema
的更多信息。¥Read more about
EntitySchema
in this section.
以下是此类实体的示例:
¥Here is an example of such entity:
import { Collection, EntitySchema } from '@mikro-orm/core';
import { Book } from './Book.js';
import { BaseEntity } from './BaseEntity.js';
/**
* @property {number} id
* @property {Date} createdAt
* @property {Date} updatedAt
* @property {string} name
* @property {string} email
* @property {number} age
* @property {boolean} termsAccepted
* @property {string[]} identities
* @property {Date} born
* @property {Collection<Book>} books
* @property {Book} favouriteBook
* @property {number} version
* @property {string} versionAsString
*/
export class Author extends BaseEntity {
/**
* @param {string} name
* @param {string} email
*/
constructor(name, email) {
super();
this.name = name;
this.email = email;
this.books = new Collection(this);
this.createdAt = new Date();
this.updatedAt = new Date();
this.termsAccepted = false;
}
}
export const schema = new EntitySchema({
class: Author,
properties: {
name: { type: 'string' },
email: { type: 'string', unique: true },
age: { type: 'number', nullable: true },
termsAccepted: { type: 'boolean', default: 0, onCreate: () => false },
identities: { type: 'string[]', nullable: true },
born: { type: DateType, nullable: true, length: 3 },
books: { kind: '1:m', entity: () => 'Book', mappedBy: book => book.author },
favouriteBook: { kind: 'm:1', type: 'Book' },
version: { type: 'number', persist: false },
},
});
不要忘记提供
name
和path
模式参数以及entity
和schema
导出。¥Do not forget to provide
name
andpath
schema parameters as well asentity
andschema
exports.
引用 kind
参数可以是以下之一(其中 SCALAR
是默认值):
¥Reference kind
parameter can be one of (where SCALAR
is the default one):
enum ReferenceKind {
SCALAR = 'scalar',
ONE_TO_ONE = '1:1',
MANY_TO_ONE = 'm:1',
ONE_TO_MANY = '1:m',
MANY_TO_MANY = 'm:n',
EMBEDDED = 'embedded',
}
我们可以像往常一样注册我们的实体:
¥We can register our entities as usual:
const orm = await MikroORM.init({
entities: [Author, Book, BookTag, BaseEntity],
dbName: 'my-db-name',
});
我们还可以将
EntitySchema
实例传递给entities
数组。¥We can also pass the
EntitySchema
instance to theentities
array.
有关纯 JavaScript 实体定义的更多示例,请查看 Express JavaScript 示例。
¥For more examples of plain JavaScript entity definitions take a look Express JavaScript example.