mongoose model multiple key types

Viewed 18

I have a simple schema as

const xpReward = new mongoose.Schema({
   ...,
   receivedFor: {
     type: Object,
     required: true
   }
});

Received for is an object which can have 2 keys and the values can be something like { "articleId": 5} or { "testId": 7}

I want to expand this receivedFor object with an required field, but keeping the possibility to add articleId or testId.

I know I can let it as in example above, because is an object and can have any form, but I want to specify the type there, to can be known in further usage.

I'm thinking at something like:

const xpReward = new mongoose.Schema({
   ...,
   receivedFor: {
     learningPath: {
       type: String,
       required: true
     },
     articleId | testId: {
       type: Number,
       required: true
     }
   }
});

I don't want to use another nested object as

receivedFor: {
   learningPath: {
     type: String,
      required: true
   },
   // in this example, the old receivedFor will become this valueFor
   // this will be just another nested level, one more parent for it
   valueFor: { 
     type: Object,
     required: true
   }
}

Can be this done somehow better? thx

1 Answers

Would likely need some hooks to go along with this, but this is the basic idea.

const xpReward = new mongoose.Schema({
    ...,
    receivedFor: {
        learningPath: {
            type: String,
            required: true
        },
        foreignId: {
            type: Number,
            required: true
        },
        foreignCollection: { // maybe even make it an enum - articleId | testId
            type: String,
            required: true
        }
    }
});

Related