Mongoose isModified 和 isNew
Mongoose isModified and isNew
我在不同的教程中看到过这个例子,我只是想知道为什么它适用于新文档。新文件是否被视为已修改?我们不应该使用 this.isNew || this.isModified
而不仅仅是 isModified 吗?
try {
if (!this.isModified("password")) {
return next();
}
let hashedPassword = await bcrypt.hash(this.password, 10);
this.password = hashedPassword;
return next();
} catch (err) {
return next(err);
}
});
关于这个的文档不是很清楚,所以让我们尝试学习一下:
schema.pre("save", async function(next) {
console.log("password isModified: ", this.isModified("password"));
console.log("isNew: ", this.isNew);
next();
});
当我们创建一个新用户时,输出将是这样的:
password isModified: true
isNew: true
所以我们看到 this.isModified("password")
是 true
。所以我们可以理解this.isModified("password")
对于新文档也是如此。
我在不同的教程中看到过这个例子,我只是想知道为什么它适用于新文档。新文件是否被视为已修改?我们不应该使用 this.isNew || this.isModified
而不仅仅是 isModified 吗?
try {
if (!this.isModified("password")) {
return next();
}
let hashedPassword = await bcrypt.hash(this.password, 10);
this.password = hashedPassword;
return next();
} catch (err) {
return next(err);
}
});
关于这个的文档不是很清楚,所以让我们尝试学习一下:
schema.pre("save", async function(next) {
console.log("password isModified: ", this.isModified("password"));
console.log("isNew: ", this.isNew);
next();
});
当我们创建一个新用户时,输出将是这样的:
password isModified: true
isNew: true
所以我们看到 this.isModified("password")
是 true
。所以我们可以理解this.isModified("password")
对于新文档也是如此。