I am using mongodb along with mongoose js in my node js application . I created a mongoose document schema called “CompanySchema” which is using “TeamSchema” (another mongoose document schema) as a sub document. Inside this “TeamSchema” it has an array defined as employees which is using “EmployeeSchema” (another mongoose document) as a subdocument. So my question is when I am trying to save the document “CompanySchema” the default value for requirement status “unmet” is not getting set. So can you guys explain me what I am doing wrong in here?
export var EmployeeSchema = new Schema({
id: {
type: String
},
requirement: {
type: {
status: {
type: String,
enum: ['met' 'unmet'],
default : 'unmet'
}
},
default: null
},
});
export var TeamSchema = mongoose.model<TeamModel>("Team", new mongoose.Schema({
id: {
type: String,
},
name: {
type: String
},
employees: [EmployeeSchema]
}));
export var CompanySchema = mongoose.model<CompanyModel>("Company", new mongoose.Schema({
id: {
type: String
},
team: TeamSchema.schema,
}));
I think there is two problems in your schema.
First, you use the Mongoose reserved keyword type
.
By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a type declaration.
Mongoose doc: typeKey
Second, you set a default value to null
, which should give you an error if you had not used the type
keyword as a property name. Try to rename type
to requirement_type
for exemple and you'll get this error:
TypeError: Invalid value for schema path `requirement.default`
Which is coherent since it precisely needs a type to set default value.
SchemaType#default(val)
Sets a default value for this SchemaType.
Mongoose doc: SchemaType-default
I do not really understand why you want to make it null
by default, but you can do it by adding for exemple a Mixed type
:
requirement: {
type: {},
requirement_type: {
status: {
type: String,
enum: ['met', 'unmet'],
default : 'unmet'
}
},
default: null
}
// => { requirement_type: null }
Or you can remove the default and you'll get:
requirement: {
requirement_type: {
status: {
type: String,
enum: ['met', 'unmet'],
default : 'unmet'
}
}
}
// => { requirement_type: { status: 'unmet' } }
Note: You must separate the enum values with a comma.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With