Mongoose SchemaTypes schema.path()函数

Mongoose SchemaTypes schema.path()函数

使用 Mongoose SchemaTypes schema.path()函数 可以获取给定路径的实例化模式类型。该函数可用于检查给定路径的模式类型和验证器。

语法:

schema.path( propertyName );

参数: 它接受一个参数,如上所述,并以下面的方式描述:

  • propertyName: 它是我们想要检查其类型的属性的名称。

返回值: 它返回模式字符串。

设置Node.js Mongoose模块:

步骤1: 使用以下命令创建Node.js应用程序:

npm init

步骤2: 创建NodeJS应用程序之后,使用以下命令安装所需模块:

npm install mongoose

项目结构: 项目的结构将会是这样的:

Mongoose SchemaTypes schema.path()函数

示例1: 下面的示例说明了Mongoose SchemaType schema.path()函数的功能。在这个示例中,我们定义了studentSchema有三个属性:姓名、学号和班级。我们将使用schema.path()函数来检查所有属性的类型。

// Require the mongoose module 
const mongoose = require('mongoose'); 
  
// Path to our cloud DataBase 
const url = 'mongodb://127.0.0.1:27017/geeksforgeeks'
  
// Connecting to database 
mongoose.set('strictQuery', false); 
  
mongoose.connect(url) 
    .then((ans) => { 
        console.log("Connected Successful") 
    }) 
    .catch((err) => { 
        console.log("Error in the Connection") 
    }) 
  
// Creating Structure of the model 
const studentSchema = new mongoose.Schema({ 
    name: { type: String }, 
    rollNumber: { type: Number }, 
    class: { type: Number }, 
  
}); 
  
console.log('Name property accepts: ', 
    studentSchema.path('name').instance); 
console.log('Roll Number property accepts: ', 
    studentSchema.path('rollNumber').instance); 
console.log('Class property accepts: ', 
    studentSchema.path('class').instance);

运行程序的步骤: 从项目的根目录中执行以下命令来运行该应用程序:

node script2.js

输出:

Mongoose SchemaTypes schema.path()函数

示例2: 下面的示例说明了Mongoose SchemaType的功能。schema.path()函数的功能。在这个示例中,我们定义了一个schema,它有一个名为name的属性,它是一个对象,具有属性firstName和lastName。我们将使用schema.path()函数检查这些属性。

// Require the mongoose module 
const mongoose = require('mongoose'); 
  
// Path to our cloud DataBase 
const url = "mongodb://localhost:27017/GFG"
  
// Connecting to database 
mongoose.set('strictQuery', false); 
  
mongoose.connect(url) 
    .then((ans) => { 
        console.log("Connected Successful") 
    }) 
    .catch((err) => { 
        console.log("Error in the Connection") 
    }) 
  
// Calling Schema class 
const Schema = mongoose.Schema; 
  
// Creating Structure of the model 
const schema = new Schema({ 
    name: { 
        type: String, 
        firstName: { 
            type: String, 
            require: true, 
        }, 
        lastName: { 
            type: String, 
            require: true, 
        } 
    } 
}); 
  
// Compile our model 
const Person = mongoose.model('Person', schema); 
  
// Inspecting the options using schema.path() function 
console.log(schema.path('name').options);

运行程序的步骤: 在项目的根目录下执行以下命令来运行应用程序:

node script.js

输出:

Mongoose SchemaTypes schema.path()函数

参考: https://mongoosejs.com/docs/schematypes.html#path

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程