mongoose schema 类型
在使用Node.js开发时,经常会使用到MongoDB进行数据存储。而Mongoose是一个优秀的MongoDB对象模型工具,可以让我们更方便地操作数据库。在Mongoose中,定义Schema是非常重要的一步,它定义了数据库中文档的结构和约束。
基本数据类型
Mongoose Schema支持多种数据类型,包括String、Number、Date、Boolean、Array等。下面我们来看几种常用的数据类型及其示例代码:
String
String类型用于存储字符串。可以指定字符串的长度、默认值、必填等属性。
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
unique: true
},
age: {
type: String,
default: '18'
}
});
Number
Number类型用于存储数字。可以指定最小值、最大值、默认值等属性。
const productSchema = new mongoose.Schema({
name: String,
price: {
type: Number,
required: true
},
stock: {
type: Number,
default: 100
}
});
Date
Date类型用于存储日期。可以指定日期范围、默认值等属性。
const postSchema = new mongoose.Schema({
title: String,
content: String,
createdAt: {
type: Date,
default: Date.now
}
});
Boolean
Boolean类型用于存储布尔值,即true或false。
const userSchema = new mongoose.Schema({
name: String,
isActive: {
type: Boolean,
default: true
}
});
Array
Array类型用于存储数组。可以指定数组元素的类型。
const projectSchema = new mongoose.Schema({
name: String,
members: {
type: [String],
default: []
}
});
复杂数据类型
除了基本数据类型之外,Mongoose Schema还支持一些复杂数据类型,如嵌套对象和引用其他Schema。下面我们来看几种常用的复杂数据类型及其示例代码:
嵌套对象
在Schema中可以定义嵌套对象,即一个字段的值是一个对象。
const addressSchema = new mongoose.Schema({
street: String,
city: String,
country: String
});
const userSchema = new mongoose.Schema({
name: String,
address: addressSchema
});
引用其他Schema
在一个Schema中可以引用另一个Schema,建立文档间的关联关系。
const authorSchema = new mongoose.Schema({
name: String,
age: Number
});
const bookSchema = new mongoose.Schema({
title: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Author'
}
});
自定义数据类型
在Mongoose Schema中,我们还可以定义自定义数据类型,以便重复使用。
function priceValidator(price) {
return price >= 0;
}
const productSchema = new mongoose.Schema({
name: String,
price: {
type: Number,
validate: [priceValidator, 'Price must be non-negative']
}
});
总结
通过本文的介绍,我们了解了Mongoose Schema中常用的数据类型,包括基本数据类型、复杂数据类型和自定义数据类型。合理地选择和定义数据类型,可以提高数据的存储效率和查询性能,同时保证数据的完整性和准确性。