4

I have this schema:

var UserSchema = new Schema({
    documento: []
});

and this types of documents:

var RgSchema = new Schema({
    tipo: 'RG',
    numero: stringType(),
    orgaoEmissor: stringType(),
    dataExpedicao: dateType()
});

var CpfSchema = new Schema({
    tipo: 'CPF',
    numero: stringType()
});

how to set different types of schema (RgSchema or CpfSchema) in the documento: []?

A kind of this:

documento: [RgSchema || CpfSchema]

1 Answer 1

2

I do not think you can achieve this in current version of mongoose. The option I would suggest you to have a common schema for the both with tipo as enum.

var CommonSchema = new Schema({
    tipo: {type:String, enum: ['RG', 'CPF']}
    numero: stringType(),
    orgaoEmissor: stringType(),
    dataExpedicao: dateType()
});

Other option is to use different ref for different Schema.

 var UserSchema = new Schema({
        documenRG: [],
        documenCPF: []

    });
Sign up to request clarification or add additional context in comments.

5 Comments

I will use the second option, because the in my situation, CPF dont have this properties orgaoEmissor: stringType(), dataExpedicao: dateType(). Thanks for the help!
How can one use the second option if the order of the array elements (with mixed types) is important?
@Tom The User schema contains a "documento" array which may look like this: [{RGref:{...}, CPFref:null}, {RGref:null, CPFref:{...}}, {RGref:{...}, CPFref:null}]. The "UserSchema" or "CommonSchema" in @Jayram's answer facilitates this.
Can we not simply do this documento: [RgSchema || CpfSchema] in latest mongoose version ^5.3.20 ....this would be the easiest and most self explanatory
I have the exact same question -> stackoverflow.com/questions/57788956/… ...can anyone help me please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.