我用猫鼬创建了一个快速应用程序。我还创建了一个保存和更新钩子,如下所示:
userSchema.pre("update", async function save(next) {
console.log("inside update")
});
userSchema.pre("update", async function save(next) {
console.log("inside save")
});
Run Code Online (Sandbox Code Playgroud)
但是每当我调用 a 时Model.findOneAndUpdate()
,都不会调用 pre hooks,save
并且update
prehook 不起作用findOneAndUpdate
吗?
正如猫鼬文档中所述,Pre 和 post save() 钩子不会在 update() 和 findOneAndUpdate() 上执行。
您需要为此使用findOneAndUpdate
钩子。但是您无法访问将使用此关键字更新的文档。如果需要访问将要更新的文档,则需要对该文档执行显式查询。
userSchema.pre("findOneAndUpdate", async function() {
console.log("I am working");
const docToUpdate = await this.model.findOne(this.getQuery());
console.log(docToUpdate); // The document that `findOneAndUpdate()` will modify
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您可以使用以下方法设置字段值this.set()
:
userSchema.pre("findOneAndUpdate", async function() {
console.log("I am working");
this.set({ updatedAt: new Date() });
});
Run Code Online (Sandbox Code Playgroud)
假设我们有这个用户架构:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: String,
updatedAt: {
type: Date,
default: Date.now
}
});
userSchema.pre("findOneAndUpdate", async function() {
console.log("I am working");
this.set({ updatedAt: new Date() });
});
module.exports = mongoose.model("User", userSchema);
Run Code Online (Sandbox Code Playgroud)
这个用户文档:
{
"updatedAt": "2020-01-30T19:48:46.207Z",
"_id": "5e33332ba7c5ee3b98ec6efb",
"name": "User 1",
"__v": 0
}
Run Code Online (Sandbox Code Playgroud)
当我们像这样更新这个用户的名字时:
{
"updatedAt": "2020-01-30T19:48:46.207Z",
"_id": "5e33332ba7c5ee3b98ec6efb",
"name": "User 1",
"__v": 0
}
Run Code Online (Sandbox Code Playgroud)
该updatedAt
字段值将被设置为用户,它会被更新。
归档时间: |
|
查看次数: |
1619 次 |
最近记录: |