我最近在使用typeorm时意识到,当我将实体定义与模型类分离并使用相应的存储库时,findOne
中的一些方法返回的是纯对象,而不是模型类实例。我想知道这是预期的行为,还是我在实现过程中丢失了一些东西。
以下代码再现了所描述的电路:
import { EntitySchema, createConnection } from 'typeorm'
class Nameable {
id: number
name: string
}
const NameableSchema = new EntitySchema<Nameable>({
name: 'nameable',
columns: {
id: { type: Number, primary: true, generated: 'increment' },
name: { type: String }
}
})
createConnection({
type: "postgres",
host: "localhost",
port: 5432,
username: "logbook",
password: "logbook",
database: "logbook",
entities: [ NameableSchema ],
synchronize: true
})
.then(databaseConnection => databaseConnection.getRepository(NameableSchema))
.then(nameableRepository => nameableRepository.findOne({ where: { id: 1 }}))
.then(findedNameable => console.log(findedNameable))
在这种情况下,考虑到我的数据库中有一个id值等于1的持久化元组,console.log(findedNameable)
将打印出以下内容:
{ id: 1, name: 'NameableName' }
然而,我期待着这样的东西:
Nameable { id: 1, name: 'NameableName' }
我已经在模型类中使用decorator进行了一些测试,在本例中,存储库方法返回的所有实例都是来自相应模型类的实例。这个使用decorator的例子确实显示了预期的行为:
import { createConnection, Entity, PrimaryGeneratedColumn, Column } from 'typeorm'
@Entity()
class Nameable {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
}
createConnection({
type: "postgres",
host: "localhost",
port: 5432,
username: "username",
password: "password",
database: "database",
entities: [ Nameable ],
synchronize: true
})
.then(databaseConnection => databaseConnection.getRepository(Nameable))
.then(nameableRepository => nameableRepository.findOne({ where: { id: 1 }}))
.then(findedNameable => console.log(findedNameable))
实际情况是,我真的希望将实体定义与模型分开,所以我还没有考虑使用装饰器来解决这个问题。
此外,我在文档中找不到任何内容指出,使用单独的实体定义会干扰存储库类的行为。
使用与模型类分离的EntitySchema定义时,需要在options
参数中指定一个target
值,指示要映射到的类。此外,name
值应等于模型类名。
以下EntitySchema定义应使问题的代码按预期工作:
const NameableSchema = new EntitySchema<Nameable>({
name: Nameable.name, // Or 'Nameable', as you wish
target: Nameable,
columns: {
id: { type: Number, primary: true, generated: 'increment' },
name: { type: String }
}
})