Mongoose Document.prototype.directModifiedPaths()函数
Document的API.prototype.directModifiedPaths()方法用于Document模型。它允许我们获取我们直接修改的字段或明确修改的字段的列表。让我们通过一个示例来理解directModifiedPaths()方法。
语法:
document.directModifiedPaths();
参数: 此方法不接受任何参数。
返回值: 此方法返回以字符串数组形式的字段列表。
设置Node.js的Mongoose模块:
步饭1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构: 数据库结构将如下所示,集合中包含以下文件。
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个userSchema模型,包括五个列或字段:“_id”,“name”,“fixedDeposit”,“interest”和“tenure”。我们修改了 interest 和 tenure 字段,并利用 directModifiedPaths() 方法获取我们直接修改的路径。
文件名: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.findOne().then(document => {
document.interest = 0.3
document.tenure = 15
console.log(document.directModifiedPaths());
});
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
[ 'interest', 'tenure' ]
示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了一个模型,它具有五个列或字段“_id”,“name”,“fixedDeposit”,“interest”和“tenure”。为了实现 directModifiedPaths() 方法的功能,我们使用了异步函数,并使用 find() 方法从数据库中获取所有文档。最后,我们使用 directModifiedPaths() 方法来获取我们修改的路径。
文件名: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 directModifiedExample2 = async () => {
const documents = await User.find();
documents[0].fixedDeposit = 1000;
console.log(documents[0].directModifiedPaths());
}
directModifiedExample2();
运行程序的步骤: 要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
[ 'fixedDeposit' ]
参考: https://mongoosejs.com/docs/api/document.html#document_Document-directModifiedPaths