Mongoose Document.prototype.isSelected()函数

Mongoose Document.prototype.isSelected()函数

Document API.prototype.isSelected() 方法 用于在Mongoose API中的Document模型上使用。它允许我们检查特定的路径或字段在查询中是否被选择以包含在结果集中。它返回一个布尔值。

语法:

document.isSelected( path )

参数: 该方法接受一个以下描述的单个参数:

  • path: 它用于指定在初始化查询时选择的路径或字段。它可以是String类型或ArrayString类型。

返回值: 该方法返回一个布尔值。如果我们选择的字段与方法提供的字段相同,则返回true,否则返回false。

设置Node.js Mongoose模块:

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

npm init

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

npm install mongoose

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

Mongoose Document.prototype.isSelected()函数

数据库结构: 数据库结构将如下所示,集合中包含以下文档。

Mongoose Document.prototype.isSelected()函数

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个userSchema模型,其中包含五个列或字段“_id”,“name”,“fixedDeposit”,“interest”和“tenure”。我们选择将“name”字段包含在结果集中。最后,我们使用 isSelected() 方法来验证“name”字段。

文件名: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, 
    fixedDeposit: Number, 
    interest: Number, 
    tenure: Number 
}); 
  
const User = mongoose.model('User', userSchema); 
  
User.find().select('name').then(document => { 
    console.log(document); 
    console.log(document[0].isSelected('name')); 
})

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

node app.js

输出:

[
  { _id: new ObjectId("638f0262cc8a382bcf3d93df"), name: 'Bhavesh' },
  { _id: new ObjectId("638f0262cc8a382bcf3d93de"), name: 'Aditya' }  
]
true

示例2: 在这个示例中,我们使用mongoose建立了数据库连接,并定义了userSchema上的模型,包含五个列或字段“_id”,“name”,“fixedDeposit”,“interest”和“tenure”。我们提供了一个要包含在结果集中的字段数组。最后,对于我们传递给 isSelected() 方法的字段,我们得到 false 作为输出,因为我们在初始化查询时没有选择这些字段。

文件名: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, 
    fixedDeposit: Number, 
    interest: Number, 
    tenure: Number 
}); 
  
const User = mongoose.model('User', userSchema); 
  
const isSelectedExample2 = async () => { 
    const document = await User 
        .findOne() 
        .select(['name', 'fixedDeposit']); 
    console.log(document); 
    console.log(document.isSelected(['tenure', 'interest'])); 
} 
isSelectedExample2();

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

node app.js

输出:

{
  _id: new ObjectId("638f0262cc8a382bcf3d93df"),
  name: 'Bhavesh',
  fixedDeposit: 8000
}
false

参考: https://mongoosejs.com/docs/api/document.html#document_Document-isSelected

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程