mongoose Document.prototype.$isEmpty()函数

mongoose Document.prototype.$isEmpty()函数

Document API.prototype.$isEmpty()方法 是在Mongoose API上使用的。它允许我们验证文档中的任何字段是否为空。如果文档对象中的任何特定字段没有值,则 isEmpty() 方法将返回true,否则返回false。让我们通过一个示例来理解 isEmpty() 方法。

语法:

document.$isEmpty( path )
JavaScript

参数: 此方法接受一个参数,如下所述:

  • path: 用于指定集合中的路径或字段。它可以是String类型或ArrayString类型。

返回值: 此方法返回布尔值。如果文档对象中的任何特定路径没有任何值,则返回true,否则返回false。

设置Node.js Mongoose模块:

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

npm init
JavaScript

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

npm install mongoose
JavaScript

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

mongoose Document.prototype.$isEmpty()函数

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

mongoose Document.prototype.$isEmpty()函数

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个userSchema模型,包含五个列或字段:“_id”、“name”、“fixedDeposit”、“interest”和“tenure”。最后,当创建一个User模型的新对象时,我们没有定义interest字段,并且在使用isEmpty()方法时,我们可以看到对于interest字段的输出为true,对于name字段的输出为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 newUser = new User( 
    { name: 'Finch', fixedDeposit: 20000, tenure: 20 } 
); 
  
console.log(newUser.isEmpty('interest')); 
console.log(newUser.isEmpty('name'));
JavaScript

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

node app.js
JavaScript

输出:

true
false
JavaScript

示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个userSchema模型,它有五个列或字段:“_id”、“name”、“fixedDeposit”、“interest”和“tenure”。在最后,当使用create()方法创建User模型的新对象时,我们通过undefined初始化了name字段,然后我们访问了isEmpty()方法,并且可以看到预期的输出。

文件名: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.create( 
    { name: undefined, fixedDeposit: 5000, interest: 0.05, } 
) 
    .then(document => { 
        console.log(document.isEmpty('name')); 
        console.log(document.isEmpty('interest')); 
    });
JavaScript

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

node app.js
JavaScript

输出:

true
false
JavaScript

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册