Skip to content

Instantly share code, notes, and snippets.

@pcorey
Last active May 22, 2018 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcorey/6713055ae234da917ca395847a4bd84b to your computer and use it in GitHub Desktop.
Save pcorey/6713055ae234da917ca395847a4bd84b to your computer and use it in GitHub Desktop.
const Schema = require("mongoose").Schema;
const mongoose = require("mongoose");
const checkSchema = new Schema(
{},
{
discriminatorKey: "type",
_id: false
}
);
const baseSchema = new Schema({
name: {
type: String,
required: true
},
checks: [checkSchema]
});
const buildReducerSchema = (n = 0) => {
if (n > 100) {
return buildRuleSchema();
}
let reducerSchema = new Schema(
{
reducer: {
type: String,
enum: ["and", "or", "nor"]
},
checks: [checkSchema]
},
{ _id: false }
);
reducerSchema
.path("checks")
.discriminator("reducer", buildReducerSchema(n + 1));
reducerSchema.path("checks").discriminator("rule", buildRuleSchema(n + 1));
return reducerSchema;
};
const buildRuleSchema = () => {
let ruleSchema = new Schema(
{
color: String
},
{ _id: false }
);
return ruleSchema;
};
baseSchema.path("checks").discriminator("reducer", buildReducerSchema());
baseSchema.path("checks").discriminator("rule", buildRuleSchema());
const Base = mongoose.model("Base", baseSchema);
Promise.resolve()
.then(() => console.log("Creating base..."))
.then(
() =>
new Base({
name: "String",
foo: "bar",
checks: [
{
type: "reducer",
reducer: "and",
checks: [
{
type: "rule",
color: "red"
}
]
}
]
})
)
.then(res => console.log(JSON.stringify(res, null, 2)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment