Mongoose Query prototype.size()函数

Mongoose Query prototype.size()函数

Mongoose 是一个用于MongoDB的对象数据建模(ODM)库。它定义了强类型模式,包括默认值和模式验证,这些模式后来被映射到MongoDB文档中。

Mongoose Query API的 size() 方法用于查找具有指定大小的字段数组的文档。

语法:

Modal.where([path]).size([val]).exec()

参数:

  • path: path 是表示字段名称的字符串,这是必需的参数。
  • val: val 是数组中元素的数量。

安装 mongoose 模块:

步骤1: 您可以访问链接来安装 mongoose 模块。您可以使用以下命令来安装此软件包。

npm install mongoose

步骤2: 安装mongoose模块后,您可以在命令提示符中使用以下命令检查您的mongoose版本。

npm version mongoose

步骤3: 之后,您只需创建一个文件夹,并添加一个文件,例如index.js。要运行此文件,您需要运行以下命令。

node index.js

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

Mongoose Query prototype.size()函数

示例1: 我们有一些顾客的数据,包括他们的姓名和游戏兴趣。在这个示例中,我们想要找到对5款游戏感兴趣的顾客。

文件名:index.js

// Require mongoose module 
const mongoose = require('mongoose'); 
  
// Set Up the Database connection 
mongoose.connect( 
    'mongodb://localhost:27017/geeksforgeeks', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}) 
  
// Defining customerSchema schema 
const customerSchema = new mongoose.Schema( 
    { name: String, interest: Array, orderCount: Number } 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model( 
    'Customer', customerSchema); 
  
// Find the number of customers who are interested in 5 games 
Customer.where("interest").size(5).exec().then((res) => { 
    console.log(res) 
});

运行应用程序的步骤:

步骤1: 确保已使用以下命令安装了mongoose模块:

npm install mongoose

步骤2: 在执行函数之前,数据库中的示例数据如下。您可以使用任何 GUI 工具或终端来查看数据库,就像我们使用 MongoDB Compass GUI 工具一样,如下所示:

Mongoose Query prototype.size()函数

步骤3: 使用以下命令运行index.js文件:

node index.js

输出:

Mongoose Query prototype.size()函数

示例2: 在这个示例中,我们将数组的大小传递给任何一个字段不包含该数组大小的数字。

// Require mongoose module 
const mongoose = require('mongoose'); 
  
// Set Up the Database connection 
mongoose.connect( 
    'mongodb://localhost:27017/geeksforgeeks', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}) 
  
// Defining customerSchema schema 
const customerSchema = new mongoose.Schema( 
    { name: String, interest: Array, orderCount: Number } 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model( 
    'Customer', customerSchema); 
  
// Find the number of customers who are interested in 500 games 
Customer.where("interest").size(500).exec().then((res) => { 
    console.log(res) 
}); 

运行应用的步骤: 使用下面的命令运行index.js文件:

node index.js

输出:

Mongoose Query prototype.size()函数

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程