【问题标题】:Mongoose schema validations not running on updateMongoose 模式验证未在更新时运行
【发布时间】:2017-10-06 04:57:40
【问题描述】:

当我使用 mongoose 更新文档时,我在运行验证时遇到了困难。有人可以看看并帮助我吗?我也在使用异步等待。

为了澄清。我正在使用 v4.9.8 的猫鼬。

这是我的架构:

import mongoose, { Schema } from "mongoose";
import uniqueValidator from "mongoose-unique-validator";
import { isEmail } from "validator";

mongoose.Promise = global.Promise;

const userSchema  = new Schema({
  username: {
    type: String,
    required: true,
    minlength: [5, "Username must be 5 characters or more"],
    unique: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    validate: {
      validator: value => isEmail(value),
      message: "invalid email address"
    }
  },
  password: {
    type: String,
    required: true,
    minlength: [8, "Password must be 8 characters or more"]
  }
}, {
  timestamps: true
});
userSchema.plugin(uniqueValidator);

const User = mongoose.model("User", userSchema);
export default User;

这是我的更新端点。

usersController.updateUser = async function(req,res){
  try {
    if(req.body.password !== undefined){
      const hashedPassword = await bcrypt.hash(req.body.password, 10);
      req.body.password = hashedPassword;
    }
    const { userID } = req.params;
    const opts = { runValidators: true };
    const results = await User.update({ _id: userID }, { $set : req.body }, opts).exec();
    console.log(results);
    return res.status(200).json();
  } catch(error){
    console.log(error);
    return res.status(500).json({ error });
  }
};

当我对结果进行控制台登录时,我得到的只是{ n: 1, nModified: 1, ok: 1 } 根本没有运行验证。请帮帮我。我已经坚持了一个半小时。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    Mongoose 和中间件不会在更新期间执行,因为这基本上是旧 mongoose 版本的原生驱动程序的传递。请参阅此link 以获得详细答案。

    后来,Mongoose 4.0 引入了在 update() 和 findOneAndUpdate() 调用上运行验证器的选项。启用此选项将为您的 update() 调用尝试 $set 或 $unset 的所有字段运行验证器。

    你也可以试试这个package 来解决你的问题。

    【讨论】:

      【解决方案2】:

      如果您的意思是 unique 验证未运行,请注意 the following

      出于技术原因,此插件要求您还将上下文选项设置为query

      所以:

      const opts = { runValidators: true, context : 'query' };
      

      【讨论】:

      • 在文档中没有注意到这一点。谢谢老哥!
      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2013-11-13
      • 2012-12-15
      • 2016-05-07
      • 2013-08-06
      • 2016-11-17
      相关资源
      最近更新 更多