在 Mongoose 中, SchemaType 是模式中单个路径的配置对象。SchemaType 说明路径应该是什么类型,如何验证该路径,路径的默认值是什么,以及其他特定于 Mongoose 的配置选项。
const schema = Schema({ name: String, age: Number });
schema.path(name) instanceof mongoose.SchemaType; // true
schema.path(age) instanceof mongoose.SchemaType; // true
SchemaType 类只是一个基类。 有几个类继承自 SchemaType 代表不同的核心 Mongoose 类型:
mongoose.Schema.Types.Stringmongoose.Schema.Types.Numbermongoose.Schema.Types.Datemongoose.Schema.Types.Buffermongoose.Schema.Types.Booleanmongoose.Schema.Types.Mixedmongoose.Schema.Types.ObjectId(或者,等效地,mongoose.ObjectId)mongoose.Schema.Types.Arraymongoose.Schema.Types.Decimal128mongoose.Schema.Types.Map
例如:
const schema = Schema({ name: String, age: Number });
schema.path(name) instanceof mongoose.SchemaType; // true
schema.path(name) instanceof mongoose.Schema.Types.String; // true
schema.path(age) instanceof mongoose.SchemaType; // true
schema.path(age) instanceof mongoose.Schema.Types.Number; // true
使用 SchemaType
您通常不必与 SchemaType 直接实例。您可以在 架构定义 。 例如下面的示例设置默认值 age 到 25 并添加一个验证器,以确保 age 至少 21 岁。
const schema = Schema({
age: {
type: Number,
default: 25,
validate: v => v >= 21
}
});
以上是您通常在 Mongoose 中声明默认值和验证器的方式。但是没有什么能阻止你将它们添加到 age 创建架构后的 SchemaType。
// Equivalent:
const schema = Schema({ age: Number });
schema.path(age).default(25);
schema.path(age).validate(v => v >= 21);
后一种语法等同于前一种,但不常用。最常见的工作案例 SchemaType 实例直接带有 嵌入式鉴别 。
假设您有一个 Order 架构和一个 Order 有一个嵌入式列表 products,每个产品可能是一本书、计算机或其他东西,每种类型的产品都可以有不同的属性。嵌入式鉴别器让数组存储符合基于每个子文档的不同模式的子文档 __t 财产。
const productSchema = new Schema({
imageURL: String,
name: String
}, { discriminatorKey: __t });
const bookSchema = new Schema({
author: String
});
const computerSchema = new Schema({
ramGB: Number
});
const orderSchema = new Schema({
createdAt: Date,
product: [productSchema]
});
// Add discriminators to the `products` SchemaType.
orderSchema.path(products).discriminator(Book, bookSchema);
orderSchema.path(products).discriminator(Computer, computerSchema);
const Order = mongoose.model(Order, orderSchema);
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END








请登录后查看评论内容