Alvaro Silvino
Alvaro Silvino

Reputation: 9733

Mongoose typeError with custom Schema

I'm trying to use discountSchema as a type. But I'm getting this error:

throw new TypeError('Undefined type at `' + path +
      ^
TypeError: Undefined type at `discount`

but if I transform to type array:

    discount: {
        type: [discountSchema],
        default:{}
    }

it works.

How can I use complex type in mongoose as this? Am I using this model in a wrong way? How can I model this object like this?

var discountSchema = new Schema({
    type: {type: String,default:'' },
    quantity: {type: Number,default:0 },
    value: {type: Number,default:0 }
});
var objectEncomendaPropertiesSchema = {
    recheios:{
        type:[String],
        default: [],
        select: true
    },
    availableEncomenda: {
        type: Boolean,
        default:false
    },
    discount: {
        type: discountSchema,
        default:{}
    }
};

Upvotes: 1

Views: 69

Answers (2)

ianaya89
ianaya89

Reputation: 4233

You cant't set embedded documents stored as single property in mongoose, they are always stored in arrays.

The closest thing to this behaviour is setting your property to an ObjectId with a ref and using the populate method to fetch it. Take a look here to see how this approach works.


Check out embedded documents docs.

There is an open issue on GitHub requesting the behaviour you want.

Upvotes: 2

Salis
Salis

Reputation: 169

are you trying to create two Schemas then wire them up?

var discountSchema = new Schema({
    type: {type: String,default:'' },
    quantity: {type: Number,default:0 },
    value: {type: Number,default:0 }
});

mongoose.model('Discount', discountSchema);

var objectEncomendaPropertiesSchema = new Schema({
    recheios:{
        type: String,
        default: '',
        select: true
    },
    availableEncomenda: {
        type: Boolean,
        default:false
    },
    discount: {
        type: Schema.Types.ObjectId,
        ref: 'Discount'
    }
})

mongoose.model('objectEncomendaProperties', objectEncomendaPropertiesSchema); 

I reference the discount in the second schema to reference to the first schema by the ObjectId
It will fetch the properties in the Discount model as a discount property in the second Schema.

Upvotes: 0

Related Questions