【问题标题】:One to one relation in typeorm mongo dbtypeorm mongo db中的一对一关系
【发布时间】: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


    【解决方案1】:

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

    除此之外,我唯一看到的(我认为这不是你的错误的原因)是你的 states 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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 2018-07-30
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      相关资源
      最近更新 更多