我正在学习TypeScript并玩弄猫鼬。我有以下架构定义(简化形式):
interface IContact extends Document {
type: string;
firstName?: string;
}
const contactSchema = new mongoose.Schema({
contactType: {
type: String,
required: true,
trim: true,
enum: ['person', 'general']
},
firstName: {
type: String,
required: function() {
return this.contactType === 'person';
},
minlength: 1,
trim: true
}})
const Contact = mongoose.model<IContact>('Contact', contactSchema);
现在,TypeScript编译器给出了以下错误:
属性'contactType'在类型'Schema |上不存在SchemaType | SchemaTypeOpts'。 属性'contactType'在'Schema'类型上不存在。
以这种方式验证必填字段,取自mongoose文档,正确(使用this
关键字),还是有其他方式?
或者,我应该以某种方式注释我的架构,TypeScript会知道我的架构上存在contactType
属性吗?
答案 0 :(得分:0)
您可以尝试一下,这对我有用:
SELECT max(t1.id) as id, t1.firstName, t1.lastName, adr.address, cty.City
FROM test t1
cross apply (select top(1) address from test t2
where t1.FirstName = t2.FirstName and
t1.LastName = t2.LastName and
t2.address is not null
order by id desc) adr(Address)
cross apply (select top(1) city from test t2
where t1.FirstName = t2.FirstName and
t1.LastName = t2.LastName and
t2.city is not null
order by id desc) cty(City)
group by t1.firstName, t1.lastName, adr.address, cty.City;
答案 1 :(得分:0)
您也可以做类似的事情
required: function() {
return ((this as unknown) as IContact).contactType === 'person';
}
或者只是
required: function() {
return (this as any).contactType === 'person';
}
在第二种情况下,使用TypeScript的含义有点丢失,但是在这种情况下,它似乎并不那么重要