Mongoose SchemaType.prototype.isRequired函数
Mongoose SchemaType.prototype.isRequired 属性是用在Mongoose API的SchemaType对象上的。它允许我们验证在任何使用mongoose模式定义的字段或路径上的必需属性。此属性不接受任何参数。让我们通过一个示例来理解 isRequired 属性。
语法:
schemaTypeObject.path( ... ).isRequired;
参数: 此属性不接受任何参数。
返回值: 此属性返回 boolean 值。如果定义架构时设置了 required 属性为 true,此方法将返回 true,如果定义架构时设置了 required 属性为 false,此方法将返回 false。
设置 Node.js 应用:
步骤 1: 使用以下命令创建一个 Node.js 应用:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
示例1: 在这个示例中,我们通过在SchemaType原型上访问它来展示isRequired属性的功能。
文件名: app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number },
rollNumber: { type: Number },
});
const Student = connectionObject.model('Student', studentSchema);
console.log(studentSchema.path('name').isRequired);
运行程序的步骤: 在项目的根目录下执行以下命令来运行应用程序:
node app.js
输出:
true
示例2: 在这个示例中,我们通过在SchemaType原型上访问isRequired属性来说明isRequired属性的功能。最后,如果我们在定义mongoose模式时没有为任何字段设置required属性值,则对于该特定字段,该属性将返回 undefined。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, required: false },
rollNumber: { type: Number },
});
const Student = connectionObject.model('Student', studentSchema);
console.log(studentSchema.path('name').isRequired);
console.log(studentSchema.path('age').isRequired);
console.log(studentSchema.path('rollNumber').isRequired);
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
true
false
undefined
参考: https://mongoosejs.com/docs/api.html#schematype_SchemaType-isRequired