正如 mongoose docs 中所述,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
});
或者如果您可以像这样使用this.set() 设置字段值:
userSchema.pre("findOneAndUpdate", async function() {
console.log("I am working");
this.set({ updatedAt: new Date() });
});
假设我们有这个用户架构:
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);
还有这个用户文档:
{
"updatedAt": "2020-01-30T19:48:46.207Z",
"_id": "5e33332ba7c5ee3b98ec6efb",
"name": "User 1",
"__v": 0
}
当我们像这样更新这个用户的名字时:
router.put("/users/:id", async (req, res) => {
let result = await User.findOneAndUpdate(
{ _id: req.params.id },
{ name: req.body.name },
{ new: true }
);
res.send(result);
});
updatedAt 字段值将设置为用户,并将更新。