【问题标题】:How do I make mongoose run validators?如何让猫鼬运行验证器?
【发布时间】:2020-12-25 08:06:35
【问题描述】:

目前我能够将密码更新为单个字符串,即使我的架构禁止这样做(要求 minLength 为 7 个字符。)我将在下面发布我的控制器代码,我的问题是,我该如何制作mongoose 验证,在保存之前。

exports.updateUser = async (req, res) => {
  const updates = Object.keys(req.body);
  const allowedUpdates = ["name", "email", "password", "age"];
  const validOp = updates.every((update) => allowedUpdates.includes(update));

  if (!validOp) {
    return res.status(400).send({ error: "invalid updates" });
  }

  try {
    const user = req.user;

    updates.forEach((update) => (user[update] = req.body[update]));
    
    await user.save();

    res.send(user);
  } catch (err) {
    res.status(400).send(err.message);
  }
};

User.js(架构、数据库):

const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
//const Task = require("../models/Task");

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      required: true,
    },
    age: {
      type: Number,
      default: 0,
      validate(value) {
        if (value < 0) {
          throw new Error("Age must be a postive number");
        }
      },
    },
    email: {
      type: String,
      unique: true,
      required: true,
      lowercase: true,
      validate(value) {
        if (!validator.isEmail(value)) {
          throw new Error("email is invalid");
        }
      },
    },
    password: {
      type: String,
      required: true,
      minLength: 7,
      validate(value) {
        if (value.toLowerCase().includes("password")) {
          throw new Error("password must not contain password");
        }
      },
    },
    tokens: [
      {
        token: {
          type: String,
          required: true,
        },
      },
    ],
    avatar: {
      type: Buffer,
    },
    verify: {
      type: String,
    },
    resetPasswordToken: {
      type: String,
    },
    resetPasswordExpires: {
      type: Date,
    },
  },
  {
    timestamps: true,
  }
);

userSchema.virtual("posts", {
  ref: "Post",
  localField: "_id",
  foreignField: "author",
});

userSchema.methods.toJSON = function () {
  const user = this;
  const userObj = user.toObject();

  delete userObj.password;
  delete userObj.tokens;
  delete userObj.avatar;

  return userObj;
};

userSchema.methods.generateAuthToken = async function () {
  const user = this;
  const token = jwt.sign({ _id: user._id.toString() }, process.env.JWT_SECRET);
  user.tokens = user.tokens.concat({ token });
  await user.save();
  return token;
};

userSchema.statics.findByCredentials = async (email, password) => {
  const user = await User.findOne({ email });
  if (!user) {
    throw new Error("unable to login!");
  }
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) {
    throw new Error("unable to login!");
  }

  return user;
};

userSchema.pre("save", async function (next) {
  const user = this;
  if (user.isModified("password")) {
    user.password = await bcrypt.hash(user.password, 8);
  }
  next()
});

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

module.exports = User;

更多信息,因为 SO 需要更多信息。

【问题讨论】:

    标签: node.js mongodb api mongoose schema


    【解决方案1】:

    Mongoose 文档显示您可以在保存函数中设置回调以处理错误。

    https://mongoosejs.com/docs/validation.html#:~:text=Validation%20is%20middleware.,manually%20run%20validation%20using%20doc.

    作为参考,这是他们的例子:

    var schema = new Schema({
    name: {
    type: String,
    required: true
    }
    });
    var Cat = db.model('Cat', schema);
    
    // This cat has no name :(
    var cat = new Cat();
    cat.save(function(error) {
    assert.equal(error.errors['name'].message,
    'Path `name` is required.');
    
    error = cat.validateSync();
    assert.equal(error.errors['name'].message,
    'Path `name` is required.');
    });
    

    【讨论】:

    • 谢谢,但我不确定这将如何帮助我进行验证?
    • 什么意思?当它执行保存功能时,如果某些 mongoose 参数未满足并中止保存,它应该抛出错误。您还可以实现诸如 express-validator 之类的东西,这样您就不必依赖数据库来进行所有验证。如果您有兴趣 (express-validator.github.io/docs)
    • 啊,我明白你的意思了!不幸的是,我没有收到任何错误,它正在保存不符合要求标准的数据。 IE。即使我的架构需要 7 个字符的密码,我也能够保存 1 个字符的密码 - 我不知道为什么会这样。有什么想法吗?
    • 您能否使用您的 User.js 模型更新帖子,以便我们查看是否有任何可能导致问题的地方?
    猜你喜欢
    • 2016-09-23
    • 2017-06-08
    • 2021-06-20
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2017-12-08
    相关资源
    最近更新 更多