Mongoose Document prototype.getChanges()函数
使用Mongoose API的prototype.getChanges()
方法可以查看对集合的文档对象所做的更改。如果您想查看数据库中受影响的字段和属性,可以在修改文档对象值之后使用此方法。
语法:
doc.getChanges()
prototype.getChanges() 方法不接受任何参数。
返回值: prototype.getChanges() 函数返回一个包含文档发生的更改的对象。
设置Node.js应用程序:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个userSchema的模型,其中有两个列“name”和“age”。最后,我们在User模型的document对象上更新字段值之前和之后两次使用getChanges()方法。在更新文档字段值之前,我们得到的是一个空对象,在更新后,我们得到了已更新的属性或字段的对象。
- app.js: 在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,
age: Number,
});
// Defining userSchema model
const User = mongoose.model("User", userSchema);
// Creating new document
User.create({ name: "User4", age: 40 }).then(doc => {
// Accessing getChanges() before modifying fields
const getChanges1 = doc.getChanges()
console.log(getChanges1)
doc.name = "User4 Updated"
// Accessing getChanges() after modifying fields
const getChanges2 = doc.getChanges()
console.log(getChanges2)
});
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
{} // before modification
{ '$set': { name: 'User4 Updated' } } //after modification
示例2: 在这个示例中,我们在更新“name”和“age”字段值后,使用 getChanges() 方法一次。在这个示例中,我们使用了异步函数来实现功能。
- app.js: 在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,
age: Number,
});
// Defining userSchema model
const User = mongoose.model("User", userSchema);
// Function in which getChanges() is being called
const getChangesFunction = async () => {
const doc = await User.create({ name: "User5", age: 50 })
doc.name = "User5 Updated"
doc.age = 500;
doc.save();
const getChanges = doc.getChanges()
console.log(getChanges)
};
// Calling the function
getChangesFunction();
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
{ '$set': { name: 'User5 Updated', age: 500 } }
参考: https://mongoosejs.com/docs/api/document.html#document_Document-getChanges