Nal*_*uza 8 find aggregation mongodb typeorm
我如何使用 Typeform MongoDB 实现一对一的关系。
我正在尝试使用聚合加入两个文档,但没有成功。
请提供一种解决方案。
实体详细信息 1.country :- _id,name 2.state :- _id,name, countryid
export class Country {
@ObjectIdColumn()
@Type(() => String)
_id: ObjectID;
@Column()
@IsString()
@IsNotEmpty()
@Index({unique: true})
name: string;
}
Run Code Online (Sandbox Code Playgroud)
@Entity()
export class State {
@ObjectIdColumn()
@Type(() => String)
_id: ObjectID;
@Column()
@IsNotEmpty()
name: string;
@ObjectIdColumn({nullable: false})
@IsNotEmpty()
countryId: ObjectID;
}
Run Code Online (Sandbox Code Playgroud)
查找代码(选择所有状态)
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,
});
}
}
Run Code Online (Sandbox Code Playgroud)
输出:- 收到 500 没有错误
{
"error": {}
}
Run Code Online (Sandbox Code Playgroud)
为了确定起见,您能否与数据库状态共享图像?
除此之外,我看到的唯一一件事(我不认为这是错误的原因)是你的states const 是一个 mongo DB 游标(AggregationCursor<T>准确地说),你应该在聚合之后添加toArray() :
const states = await stateRepository.aggregate({
...
}).toArray();
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您的请求仅返回一个国家/地区,您可能应该添加一个$unwind ,如下所示:
$unwind: {
path: '$country',
includeArrayIndex: '0',
preserveNullAndEmptyArrays: false
}
Run Code Online (Sandbox Code Playgroud)
这种方式而不是有:
states = [{ id: 'yourStateName', country : [{id: 'yourCountryId', name: 'countryName' }], name: 'yourStateName']
Run Code Online (Sandbox Code Playgroud)
你将拥有:
states = [{ id: 'yourStateName', country : {id: 'yourCountryId', name: 'countryName' }, name: 'yourStateName']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1443 次 |
| 最近记录: |