One to one relation in typeorm mongo db

Viewed 2547

How I achieve a one-to-one relationship using Typeform MongoDB.

I m trying to join two documents using aggregation but not achieve success.

Please provide one solution.

Entity details 1.counrty :- _id,name 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;

}

find code(select all state)

 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,
            });
        }
    }

Output:- receive 500 with no error

{
    "error": {}
}
1 Answers

Could you share images with the state of your DB just to be sure ?

Apart from that the only thing I see (and I don't think it's the cause of your error) is that your states const is a mongo DB cursor (AggregationCursor<T> to be exact), you should add toArray() after your aggregate :

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

And by the way if your request only returns one country you should probably add an $unwind like this :

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

This way instead of having :

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

You'll have :

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