Mongoose SchemaType选项
Mongoose 是一个常见的JavaScript库,提供了与MongoDB的强大接口,MongoDB是一种NoSQL数据库,它以JSON格式存储数据。它被设计成易用和多功能的,使得从你的Node.js应用程序中使用MongoDB变得简单。
在Mongoose中, schema type 是模式的属性,它定义了MongoDB集合中字段的类型、必需性和其他特性。模式类型用于验证存储在集合中的数据,并定义数据在数据库中的存储方式。您可以通过指定字段的类型和任何所需的选项来定义Mongoose模式中的模式类型。
Mongoose模式类型有多个选项,您可以使用这些选项来自定义模式的行为。一些适用于模式类型的选项包括:
required: 此选项指定字段是否是必需的。如果设置为true,则该字段在所有文档中都是必需的。如果不指定此字段,默认值将为false。
default: 此选项为字段指定默认值。如果在新文档中未指定字段的值,则将使用默认值。
- unique: 此选项指定字段中的值是否必须在集合中的所有文档中是唯一的(例如:用户名字段)。
- index: 此选项指定是否为字段创建索引。索引可以提高涉及该字段的查询和其他操作的性能。
- sparse: 此选项指定是否为字段创建稀疏索引。稀疏索引仅包括具有索引字段的值的文档。
- validate: 此选项允许您为字段指定验证函数。当保存新文档时,将调用该函数,如果验证函数返回错误,则不会保存该文档。
- alias: 此选项允许您为字段指定别名。别名可以在查询和其他操作中使用,而不是实际字段名。
- get和set: 这些选项允许您为字段指定getter和setter函数。当访问字段时,将调用getter函数,当设置字段时,将调用setter函数。
示例1: 在下面的示例中,我们创建了一个只包含一个名为name的字段的模式,该字段的类型为String,是必需的,具有默认值’John Doe’,应是唯一的,该字段的索引将被创建,默认设置为true,还将包括一个稀疏索引,字符串的长度应大于3,具有一个名为’full_name’的别名。此外,此模式具有getter和setter函数,当访问字段时,它将变为大写,当设置字段时,它将变为小写。
// Creating an example schema
// using different schema type options
const mongoose = require('mongoose');
// Defining schema
let schemaClass = new mongoose.Schema({
name: {
type: String,
required: true,
default: 'John Doe',
unique: true,
index: true,
sparse: true,
validate: (value) => value.length > 3,
alias: 'full_name',
get: (value) => value.toUpperCase(),
set: (value) => value.toLowerCase()
}
});
// creating model from the schema
let Schema = mongoose.model('Schema', schemaClass);
let schema1 = new Schema({
name: "GeeksForGeeks"
});
// will have a default value of John Doe
let schema2 = new Schema({});
console.log(schema1);
console.log(schema2);
输出结果:
示例2: 下面的示例是一本图书的架构,具有标题字段,类型为字符串且为必填项,作者字段类型为字符串且为必填项,出版日期字段类型为日期且为必填项,页数字段类型为数字且为必填项,出版商字段类型为字符串,封面图片URL字段类型也是字符串。
// Creating an example schema
const mongoose = require('mongoose');
// Defining schema
let bookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
publishedDate: {
type: Date,
required: true
},
pageCount: {
type: Number,
required: true
},
publisher: String,
coverImageUrl: String
});
// creating model from the schema
let Book = mongoose.model('Book', bookSchema);
let book = new Book({
title: "DSA",
author: "GeeksForGeeks",
publishedDate: new Date(),
pageCount: 512,
});
console.log("Book:", book);
输出: