猫鼬-更新时如何验证模型?

时间:2020-05-10 18:24:46

标签: javascript node.js express mongoose model

我有以下模型。当我尝试使用错误的信息进行创建时,这是不允许的,但是如果我尝试编辑该信息,则允许它。我该如何预防?

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,
  });

1 个答案:

答案 0 :(得分: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.');
  }
};
相关问题