I have a collection User
that has two fields of the collection Country
embedded in itas a subdocument. The Country
collection is used as an enumerator and is used to reference before inserting it into the User
collection. I want to apply this logic to my GraphQL and Typegoose project.
In the user.schema.ts file:
import { Field, InputType, ObjectType } from 'type-graphql';
import { prop as Property, Ref } from '@typegoose/typegoose';
import { Country } from './country.model';
@ObjectType()
@InputType('UserInput')
export class User {
@Field(type => ID)
@Property({ required: true })
public _id!: string;
@Field(type => Country)
@Property({ ref: 'Country', required: true })
public country!: Ref<Country>;
}
In the country.schema.ts file:
import { Field, ID, InputType, Int, ObjectType } from 'type-graphql';
import { modelOptions, prop as Property, Ref } from '@typegoose/typegoose';
@modelOptions({ schemaOptions: { collection: 'Country' } })
@ObjectType()
@InputType('CountryInput')
export class Country {
@Field(type => ID)
@Property({ required: true })
_id!: string;
@Field()
@Property({ required: true })
name!: string;
@Field()
@Property({ required: true })
alpha2!: string;
@Field()
@Property({ required: true })
alpha3!: string;
@Field()
@Property({ required: true })
numeric!: string;
}
The user collection has a subdocument that is named "Country". The subdocument only has "id" and "name" from the "Country" collection.
{
"_id" : "7392798430",
"country" : {
"id" : "69",
"name" : "Switzerland"
}
}
This is what a document in the "Country" collection looks like:
{
"_id" : "6786876687",
"name" : "Switzerland",
"alpha2" : "CH",
"alpha3" : "CHE",
"numeric" : "789"
}
I want to be able to reference the country table every time I create a user. Currently, I'm attempting to query the user with the country as a property, and it gives me the error:
Cannot return null for non-nullable field User.country. Every user already has a country subdocument. None of them are null. It is required.
I'm not even being able to query it normally. I want to test by querying it first, and then inserting it into the user table a country not available in the country table, to test whether it would throw an error or not.
I'm using NestJS if that matters.