类型中的一对一关系 mongo db.



如何使用Typeform MongoDB实现一对一的关系。

我正在尝试使用聚合连接两个文档,但没有成功。

请提供一个解决方案。

实体详细信息 1.名称 :- _id,名称 2.状态:- _id,姓名,国家ID

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": {}
}

您能否与数据库的状态共享图像以确保?

除此之外,我唯一看到的(我不认为这是导致您错误的原因(是您的状态const 是一个 mongo DB 游标(确切地说AggregationCursor<T>(,您应该在聚合后添加toArray((:

const states = await stateRepository.aggregate({ 
...
}).toArray(); 

顺便说一下,如果您的请求只返回一个国家/地区,您可能应该添加这样的$unwind

$unwind: {
path: '$country',
includeArrayIndex: '0',
preserveNullAndEmptyArrays: false
}

这样而不是有:

states = [{ id: 'yourStateName', country : [{id: 'yourCountryId', name: 'countryName' }], name: 'yourStateName']

您将拥有:

states = [{ id: 'yourStateName', country : {id: 'yourCountryId', name: 'countryName' }, name: 'yourStateName']

最新更新