为什么不触发FindOneAndUpdate上的猫鼬验证器

时间:2019-01-26 09:05:03

标签: node.js mongoose

我正在使用Node.js Mongoose和Express构建RESTful API,但遇到一个问题,当我更新一个模型时,并且该模型具有用于某些字段的验证器时,我没有收到错误验证后,该模型会在未经验证的情况下进行更新。

Task.model.js简化

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const TaskSchema = new Schema({
    isCanceled: { 
        type: Boolean, 
        default: false 
    },
    cancelReason: {
        type: String,
        required: function() { return this.isCanceled; }
    },
    canceledBy: {
        type: Schema.Types.ObjectId, 
        ref: 'User', 
        required: function() { return this.isCanceled; } 
    }
});

module.exports = mongoose.model('Task', TaskSchema);

Task.controller.js

exports.cancel = async function(req, res) {
    await taskService.cancel(req.params.id, req.body)
        .then(task => res.status(200).json({ status: 201, data: task, message: 'Succesfull' }))
        .catch(err => res.status(404).json({ status: 404, message: err.message }))
}

Task.service.js

exports.cancel = async function(id, cancelParams) {
    const canceledTask = await Task.findOneAndUpdate({ _id: id }, { $set: cancelParams }, { new: true } );
    if (!canceledTask) throw new Error('Task not found.');

    return canceledTask;
}

在Task.service.js中,即使isCanceledcancelReason字段为空,如果我将canceledBy设置为true,任务也会得到更新。我还尝试过在runValidators函数中设置contextFindOneAndUpdate

0 个答案:

没有答案