Mongoose Aggregate.prototype.model()函数

Mongoose Aggregate.prototype.model()函数

在Mongoose API中, Aggregate.prototype.model() 方法用于执行聚合任务。它允许我们更改特定聚合管道的模型。该方法接受模型对象并返回该特定聚合管道的模型对象。让我们通过一个示例来了解 model() 方法。

语法:

aggregate.model( model_name );

参数: 该方法接受单个参数,如下所讨论:

  • model: 该方法以模型对象作为参数。

返回值: 该方法返回将执行聚合管道的模型对象。

设置Node.js应用:

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

npm init

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

npm install mongoose

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

Mongoose Aggregate.prototype.model()函数

示例1: 在这个示例中,我们通过在Student模型上定义聚合管道来演示model()方法的功能。

文件名: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); 
  
const aggregate =  
    Student.aggregate([{ $project: { age: 1 } }]) 
      
console.log(aggregate.model() === Student);

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

node app.js

输出:

true

示例2: 在这个示例中,我们通过将Customer模型传递给Student模型聚合管道返回的聚合对象来演示model()方法的功能。

文件名: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); 
  
const Customer = connectionObject.model( 
    'Customer', new mongoose.Schema({ 
        name: String, 
        address: String, 
        orderNumber: Number, 
    })); 
  
const aggregate = Student.aggregate([{ $project: { age: 1 } }]) 
  
aggregate.model(Customer); 
  
console.log(aggregate.model() === Customer);

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

node app.js

输出:

false

参考资料: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-model

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程