Nimrod
Nimrod

Reputation: 422

a missing sub document turns into a subdocument with undefined values, and schema validation fails

I have a schema.graphqls that looks like this:

type House {
  id: ID!
  rooms: Int!
  address: String!
  owner: Owner
}

type Owner: {
     name: String!,
     age: Int!
}

and a complementing mongoose schema:

export default class House {
    static schema = {
        rooms: Number
        address: String,
        owner: {
            type : {
                name: String,
                age: Number
            },
            required: false
        }
    };
}

and I have an object in my mongodb looking like this (notice owner is missing intentionally):

ObjectId("xxx") {
  rooms: 3,
  address: "the street"
}

I'm trying to retrieve this document, the owner subdocument is missing (which is fine, its not mandatory). The mongoose result fills this missing subdocument with undefined attributes,

ObjectId("xxx") {
  rooms: 3,
  address: "the street"
  owner : {
     name: undefined
     age: undefined
}

which fails the schema validations (since indeed name and age are mandatory, if subdocument exists).

the actual error i'm getting is:

Resolve function for "House.owner" returned undefined

Could you possibly point me to whatever i'm doing wrong here?

thanks in advance

Upvotes: 1

Views: 144

Answers (1)

Nimrod
Nimrod

Reputation: 422

Following a direction from @Neil Lunn, I realised the problem is in the mongoose schema, which led me to add required: false - which wasn't enough, but after adding also default: null voila.

problem solved. error gone. final mongoose schema, to whom it may be of interest:

export default class House {
    static schema = {
        rooms: Number
        address: String,
        owner: {
            type : {
                name: String,
                age: Number
            },
            required: false,
            default: null
        }
    };
}

Upvotes: 1

Related Questions