Nalawala Murtaza
Nalawala Murtaza

Reputation: 4810

One to one relation in TypeORM mongo db

How to model a one-to-one relationship using TypeORM MongoDB?

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

Entity details:

  1. country :- _id, name
  2. state :- _id, name, countryid
@Entity()
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;

}

Search code (to select the whole 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: I receive 500 with no error detail.

{
    "error": {}
}

Upvotes: 10

Views: 3567

Answers (1)

tiago ERNST
tiago ERNST

Reputation: 35

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']

Upvotes: 0

Related Questions