Mongoose Document.prototype.$isDefault()函数

Mongoose Document.prototype.$isDefault()函数

Document API.prototype.$isDefault() 方法用于 Document 模型上。它允许我们检查模式中的特定字段是否具有默认值。在定义模式时,我们可以为字段设置默认值。让我们使用一个示例来理解 isDefault() 方法。

语法:

document.$isDefault( path );
JavaScript

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

  • path: 用于指定我们要验证isDefault()功能的路径或字段名。

返回值: 该方法返回一个布尔值,指定我们提供给方法的路径是否设置为默认值。

设置Node.js Mongoose模块:

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

npm init
JavaScript

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

npm install mongoose
JavaScript

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

Mongoose Document.prototype.$isDefault()函数

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

Mongoose Document.prototype.$isDefault()函数

示例1: 在该示例中,我们使用mongoose建立了一个数据库连接,并定义了userSchema上的模型,它有五列或字段“_id”,“name”,“fixedDeposit”,“interest”和“tenure”。在创建User模型的新文档时,我们没有为tenure字段分配任何值,以便在执行时分配默认值。最后,我们使用isDefault()方法验证tenure字段是否具有默认值。

文件名: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: { type: Number, default: 6 } 
}); 
  
const User = mongoose.model('User', userSchema); 
  
const newUser = new User( 
    { name: "Denial", fixedDeposit: 2000, interest: 0.10 } 
); 
  
console.log(newUser); 
  
console.log(newUser.$isDefault('tenure'));
JavaScript

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

node app.js
JavaScript

输出:

{
  name: 'Denial',
  fixedDeposit: 2000,
  interest: 0.1,
  tenure: 6,
  _id: new ObjectId("63917e3942ea51d56bff200a")
}
true
JavaScript

示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了模型,该模型有五个列或字段“_id”,“name”,“fixedDeposit”,“interest”和“tenure”。这是另一个 isDefault() 方法的示例,但在这个示例中,我们为所有字段分配了值,这就是为什么在使用 isDefault() 方法对 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: { type: Number, default: 6 } 
}); 
  
const User = mongoose.model('User', userSchema); 
  
User.create( 
    { 
        name: "Denial", fixedDeposit: 2000, 
        interest: 0.10, tenure: 12 
    }) 
    .then(newDocument => { 
        console.log(newDocument); 
        console.log(newDocument.$isDefault('name')); 
    });
JavaScript

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

node app.js
JavaScript

输出:

{
  name: 'Denial',
  fixedDeposit: 2000,
  interest: 0.1,
  tenure: 12,
  _id: new ObjectId("639180857bb3df8284caef2b"),
  __v: 0
}
false
JavaScript

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册