The current schema looks like this:
const schema = new mongoose.Schema(
filters: {
type: Object,
default: {}
}
);
Sample Input Document:
{
filters: {
field1: "5a934e000102030405000001",
field2: "5a934e000102030405000002",
field3: "5a934e000102030405000003"
}
}
The filters
object property will store dynamic properties/fields but all will be ObjectId
type,
Currently, I am using pre-hook and lodash methods to convert type into ObjectId type,
SchemaObj.pre('save', function (next) {
this.filters = _.reduce(this.filters, (r, v, k) => v ? { ...r, [k]: mongoose.Types.ObjectId(v) } : r, {});
next();
});
Is there any way to define ObjectId type of dynamic object fields?
I am expecting something like this if mongoose provide any other approach:
const schema = new mongoose.Schema(
filters: {
type: {
*: mongoose.Types.ObjectId
}
}
);
CodePudding user response:
You can define the field as a Map
const schema = new mongoose.Schema(
filters: {
type: Map,
of: mongoose.Schema.Types.ObjectId
}
);