Nic*_*lli 5 javascript mongoose mongodb typescript
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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
运行此代码时遇到的两个错误是:
为了对required函数进行类型检查,TypeScript 需要知道调用this时将引用什么类型的对象required。默认情况下,TypeScript 猜测(错误地)required将作为包含对象字面量的方法调用。由于 Mongoose 实际上会required使用thisset调用您正在定义的结构的文档,因此您需要为该文档类型定义一个 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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1395 次 |
| 最近记录: |