【问题标题】:Mongoose - How to validate model when updating?Mongoose - 更新时如何验证模型?
【发布时间】:2020-08-26 05:35:49
【问题描述】:

我有以下型号。当我尝试使用错误信息创建时,它不允许,但如果我尝试编辑信息,则允许它。我怎样才能防止这种情况发生?

var userSchema = new Schema({
  cartaoCidadao: {
    type: String,
    required: true,
    index: {
      unique: true,
    },
    match: /[0-9]{8}/,
  },
  password: { type: String, required: true },
  histórico: [
    {
      type: Schema.Types.ObjectId,
      ref: "Request",
    },
  ],
  role: { type: String },

  estado: { type: String, enum: ["Infetado", "Suspeito", "Curado"] },

});

userController.updateUserPassword = async (req, res) => {
  const oldUser = await User.findByIdAndUpdate(req.params.userId, {
    password: req.body.password,
  });

  //nao permitir password vazia
  const newUser = await User.findById(req.params.userId);
  res.send({
    old: oldUser,
    new: newUser,
  });
};

userController.updateUserState = async (req, res) => {
  const oldUser = await User.findByIdAndUpdate(req.params.userId, {
    estado: req.body.estado,
  });

【问题讨论】:

    标签: javascript node.js express mongoose model


    【解决方案1】:

    updateValidators默认关闭,需要在更新操作中指定runValidators: true选项。

    userController.updateUserPassword = async (req, res) => {
      try {
        const oldUser = await User.findByIdAndUpdate(
          req.params.userId,
          {
            password: req.body.password,
          },
          {
            runValidators: true,
          }
        );
    
        //nao permitir password vazia
        const newUser = await User.findById(req.params.userId);
        res.send({
          old: oldUser,
          new: newUser,
        });
      } catch (err) {
        console.log('Error: ', err);
        res.status(500).send('Something went wrong.');
      }
    };
    

    【讨论】:

    • 在哪里激活它?
    • 我已经做到了,现在每当我尝试更新为无效密码时,邮递员只会停留在“发送请求”。假设会发生这种情况吗?
    • @FábioPires 你能像我在更新的答案中那样添加一个 try catch 块,并检查 api 控制台是否有错误?
    • 它起作用了。愚蠢的问题,与其发送出错信息,不如发送密码无效或者我应该避免向用户显示错误是什么?
    • @FábioPires 是的,如果是验证错误会更好,检查我的答案here
    猜你喜欢
    • 2016-11-18
    • 2022-01-15
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多