Mongoose SchemaType.prototype.path 属性

Mongoose SchemaType.prototype.path 属性

Mongoose API 的 Mongoose SchemaType.prototype.path 属性用于 SchemaType 对象。它允许我们从模式中获取 SchemaType 的路径或字段。它可以在任何模式对象上调用,并能提供特定模式的路径。让我们通过一个示例来理解 path 属性。

语法:

schemaTypeObject.path( <name> ).path;

参数:

此属性不接受任何参数。

返回值:

此属性返回路径或字段名称。

设置Node.js Mongoose模块:

步骤1:

使用以下命令创建一个Node.js应用程序:

npm init

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

npm install mongoose

项目结构: 项目结构将如下所示:

Mongoose SchemaType.prototype.path 属性

示例1: 下面的示例演示了Mongoose SchemaType的功能 path 属性。在这个示例中,我们定义了一个studentSchema,它有四个属性或字段:name、age、rollNumber和parents。最后,我们使用schemaTypeObject.path()方法来获取name字段的路径。

文件名: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 }, 
    age: { type: Number }, 
    rollNumber: { type: Number }, 
    parents: { 
        fatherName: { type: String }, 
        motherName: { type: String } 
    } 
}); 
  
const StudentModel = connectionObject.model 
    ('Student', studentSchema); 
  
let path = studentSchema.path('name').path; 
  
console.log(path);

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

node app.js

输出:

name

示例2: 下面的示例展示了Mongoose SchemaType路径属性的功能。在这个示例中,我们定义了studentSchema,有四个属性或字段:name、age、rollNumber和parents。最后,我们使用路径属性获取嵌套对象属性的路径,即parents.fatherName和parents.motherName。

文件名: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 }, 
    age: { type: Number }, 
    rollNumber: { type: Number }, 
    parents: { 
        fatherName: { type: String }, 
        motherName: { type: String } 
    } 
}); 
  
console.log(studentSchema.path('parents.fatherName').path); 
console.log(studentSchema.path('parents.motherName').path);

运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:

node app.js

输出:

parents.fatherName
parents.motherName

参考资料: **** https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-path

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程