import mongoose, { Schema, model } from "mongoose";
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, "Too few eggs"],
max: 12
},
bacon: {
type: Number,
required: [true, "Why no bacon?"]
},
drink: {
type: String,
enum: ["Coffee", "Tea"],
required: function() {
return this.bacon > 3;
}
}
});
运行此代码时遇到的两个错误是:
答案 0 :(得分:1)
为了对required
函数进行类型检查,TypeScript需要知道在调用this
时将引用的对象类型required
。默认情况下,TypeScript猜测(错误地)required
将作为包含对象文字的方法被调用。由于Mongoose实际上会调用required
并将this
设置为您要定义的结构的文档,因此您需要为该文档类型定义一个TypeScript接口(如果您还没有一个TypeScript接口) ),然后为this
函数指定一个required
参数。
interface Breakfast {
eggs?: number;
bacon: number;
drink?: "Coffee" | "Tea";
}
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, "Too few eggs"],
max: 12
},
bacon: {
type: Number,
required: [true, "Why no bacon?"]
},
drink: {
type: String,
enum: ["Coffee", "Tea"],
required: function(this: Breakfast) {
return this.bacon > 3;
}
}
});
答案 1 :(得分:0)
在 tscongig.json
内的 compilerOptions
文件中,我更改了以下内容并且它起作用了:
"noImplicitThis": false,
...
/* Raise error on 'this' expressions with an implied 'any' type. */