如何在mongoose子文档中configuration默认​​的枚举值?

我在我的节点js应用程序中使用mongodb与mongoosejs。 我创build了一个名为“CompanySchema”的mongoose文档模式,它使用“TeamSchema”(另一个mongoose文档模式)作为子文档。 在这个“TeamSchema”中,它有一个数组,定义为使用“EmployeeSchema”(另一个mongoose文档)作为子文档的员工。 所以我的问题是,当我试图保存文档“CompanySchema”的需求状态“未满足”的默认值没有得到设置。 那么你们能解释一下我在这里做错了吗?

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, })); 

我认为你的模式有两个问题。

首先,您使用Mongoose保留的关键字type

默认情况下,如果在模式中有一个带有“type”键的对象,mongoose会将其解释为types声明。

Mongoose doc: typeKey

其次,将默认值设置为null ,如果您没有使用type关键字作为属性名称,则会给出错误信息。 尝试将type重命名为requirement_type ,例如,你会得到这个错误:

 TypeError: Invalid value for schema path `requirement.default` 

这是一致的,因为它正好需要一个types来设置默认值。

的SchemaType#默认值(VAL)
为此SchemaType设置默认值。

Mongoose文档: SchemaType-default

我不明白为什么你想默认为null ,但你可以通过添加例如Mixed type

 requirement: { type: {}, requirement_type: { status: { type: String, enum: ['met', 'unmet'], default : 'unmet' } }, default: null } // => { requirement_type: null } 

或者你可以删除默认,你会得到:

 requirement: { requirement_type: { status: { type: String, enum: ['met', 'unmet'], default : 'unmet' } } } // => { requirement_type: { status: 'unmet' } } 

注意:您必须用逗号分隔枚举值。