猫鼬findOneAndUpdate:如何仅在更新的字段而不是所有字段上运行Validator?

时间:2019-09-16 18:57:18

标签: node.js mongoose

这不是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

0 个答案:

没有答案