如何使猫鼬运行验证器?

时间:2020-09-06 20:11:18

标签: node.js mongodb api mongoose schema

目前,即使我的模式禁止这样做(我要求minLength为7个字符),我仍然可以将密码更新为单个字符串。我将在下面发布控制器代码,我的问题是,我该如何制作猫鼬在保存之前先进行验证。

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需要更多信息。

1 个答案:

答案 0 :(得分:0)

猫鼬文档显示,您可以在保存函数中设置回调以解决错误。

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

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

export default function Home() {
return (
<Card>
  <CardContent>
    <FormikStepper
      initialValues={{
   
      }}
      onSubmit={async (values) => {
        await sleep(3000);
        console.log('values', values);
      }}
    >
      <FormikStep label="Certifications">
        <Box paddingBottom={2}>
        <Certifications   ></Certifications>
        </Box>
      </FormikStep>
      <FormikStep 
        label="loginPageF"

      >
        <Box paddingBottom={2}>
        <SoForm ></SoForm>