【问题标题】:How to enable the Mongoose Update Validator - Node如何启用 Mongoose 更新验证器 - 节点
【发布时间】:2021-03-23 16:13:35
【问题描述】:

这是我的架构:

const personSchema = new mongoose.Schema({
    name: {
        type: String,
        minlength: 3,
        unique: true,
        required: true
    },

    number: {
        type: String,
        minlength: 8,
        required: true
    }
})

我的更新代码:

app.put('/api/persons/:id', (request, response, next) => {
const body = request.body
const person = {
    name: body.name,
    number: body.number
}

let opts = {
    runValidators: true
};

Person.findByIdAndUpdate(request.params.id, person, { new: true }, opts)
    .then(updatedPerson => {
        response.json(updatedPerson)
    })
    .catch(error => next(error))})

我尝试更新信息,但验证不适用于更新,它在创建新人员时有效。我知道 Mongoose 更新验证器默认是关闭的,我尝试了很多方法来启用它,但是它不起作用,谁能帮助我吗?

【问题讨论】:

    标签: node.js mongodb validation mongoose


    【解决方案1】:

    将您的选项放在第三个参数中:

    Person.findByIdAndUpdate(request.params.id, person, { new: true, runValidators: true })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 2022-01-10
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      相关资源
      最近更新 更多