【发布时间】:2023-03-17 23:15:01
【问题描述】:
我如何使用 Typeform MongoDB 实现一对一的关系。
我正在尝试使用聚合连接两个文档,但没有成功。
请提供一种解决方案。
实体详情 1.国家:- _id,名称 2.state :- _id,name,countryid
export class Country {
@ObjectIdColumn()
@Type(() => String)
_id: ObjectID;
@Column()
@IsString()
@IsNotEmpty()
@Index({unique: true})
name: string;
}
@Entity()
export class State {
@ObjectIdColumn()
@Type(() => String)
_id: ObjectID;
@Column()
@IsNotEmpty()
name: string;
@ObjectIdColumn({nullable: false})
@IsNotEmpty()
countryId: ObjectID;
}
查找代码(选择所有状态)
let stateRepository: StateRepository = getCustomRepository(StateRepository);
try {
const states = await stateRepository.aggregate([
{
$lookup:
{
from: 'country',
localField: 'countryId',
foreignField: '_id',
as: 'country'
}
}
]);
res.status(200).send({
data: states
});
}
catch (exception) {
res.status(500).send({
error: exception,
});
}
}
输出:- 收到 500 且没有错误
{
"error": {}
}
【问题讨论】:
标签: mongodb find aggregation typeorm