I’m working on a project that has a document that will need to have different information depending on the type of the document. A simplfied example might be like this:
const blueSchema = new mongoose.Schema({
typeOfBlue: {
type: String,
enum: [`Ocean`, `Sky`]
}
})
const redSchema = new mongoose.Schema({
typeOfRed: {
type: String,
enum: [`Wine`, `Blood`]
}
})
const exampleSchema = new mongoose.Schema ({
colour:
{
type: String,
enum: [`Blue`, `Red`],
required: true
},
colourInformation: //This should be redSchema || blueSchema depending on the value of colour
})
The problem is that I’m unable to reference the value of the document before it’s initialised so I can’t figure out how to word any function or such so that it would not result in an undefined result.
Mostly I’ve tried things like the bellow but as I mentioned, it usually results in an undefined output or else mongoose can’t access the value before it’s saved.
function validateColour(colour) {
if (colour === `Blue`) {
return blueSchema
} else if (colour === `Red`) {
return redSchema
}
}
const blueSchema = new mongoose.Schema({
typeOfBlue: {
type: String,
enum: [`Ocean`, `Sky`]
}
})
const redSchema = new mongoose.Schema({
typeOfRed: {
type: String,
enum: [`Wine`, `Blood`]
}
})
const exampleSchema = new mongoose.Schema ({
colour:
{
type: String,
enum: [`Blue`, `Red`],
required: true
},
colourInformation: validateColour(this.colour)
})