这不是Mongoose findOneAndUpdate and runValidators not working的副本
或runValidators option not working on findByIDAndUpdate or findOneAndUpdate using mongoose
我正在将Mongoose ODM用于Node.js
当我在最后一行上使用选项{ runValidators: true }
运行以下代码时,出现错误,因为它也在尝试验证电子邮件地址(更新中未提供)。如果删除{ run Validators: true }
,则代码可以正常运行,但是不会对更新后的字段进行验证。如何让Mongoose在仅我要更新的字段上而不是在数据库条目中的所有字段上运行验证?
const mongoose = require("mongoose")
const User = mongoose.model("User", {
name: {
type: String
},
email: {
type: String
}
}
const update = {
name: "Jessica"
}
User.findByIdAndUpdate(id, update, { new: true, runValidators: true })
设置{ runValidators: true }
时出现的错误是:TypeError: Cannot read property '_update' of undefined