Mongoose Document Model.prototype.modelName函数

Mongoose Document Model.prototype.modelName函数

Mongoose API的 Model.prototype.modelName 属性用于返回模型的名称。

语法:

Model.prototype.modelName.db

返回: Model.prototype.modelName 属性返回模型的名称。

设置Node.js应用程序:

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

npm init

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

npm install mongoose

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

Mongoose Document Model.prototype.modelName函数

示例1: 在这个示例中,我们使用mongoose建立了数据库连接,并定义了一个userSchema模型,拥有两个列或字段“name”和“age”。最后,我们使用User模型上的modelName属性来返回模型的名称。

  • app.js: 将下面的代码写入app.js文件中:
// Require mongoose module 
const mongoose = require('mongoose'); 
  
// Set Up the Database connection 
mongoose.connect( 
    'mongodb://localhost:27017/geeksforgeeks', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}) 
  
const userSchema = new mongoose.Schema( 
    { name: String, age: Number } 
) 
  
// Defining userSchema model 
const User = mongoose.model('User', userSchema); 
  
const output = User.modelName 
console.log("Model Name is:", output)

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

node app.js

输出:

Model Name is: User

示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在studentSchema上定义了模型,其中有三列或字段“name”、“father_name”和“mother_name”。最后,我们使用Student模型上的db属性,它将返回正在被Student模型使用的连接。

  • app.js: 在app.js文件中写入以下代码:
// Require mongoose module 
const mongoose = require('mongoose'); 
  
// Set Up the Database connection 
mongoose.connect( 
    'mongodb://localhost:27017/geeksforgeeks', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}) 
  
const studentSchema = new mongoose.Schema( 
    { 
        name: String, father_name: 
            String, mother_name: String 
    } 
) 
  
// Defining studentSchema model 
const Student = mongoose.model('Student', studentSchema); 
  
// Accessing modelName property on Student model 
const output = Student.modelName 
console.log("Model Name is:", output)

运行程序的步骤:

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

node app.js

输出:

Model Name is: Student

参考: https://mongoosejs.com/docs/api/model.html#model_Model-modelName

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程