harry young
harry young

Reputation: 770

How do I make mongoose run validators?

currently I'm able to update passwords to a single character string, even though my schema prohibits this (by requiring a minLength of 7 chars.) I'll post my controller code below and my question is, how can i make mongoose validate, prior to saving.

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 (schema, database thingy):

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;

More info because SO requires more.

Upvotes: 1

Views: 1529

Answers (1)

Robster
Robster

Reputation: 222

The Mongoose docs show that you can set up a callback inside your save function for errors.

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

For reference, this is their example:

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.');
});

Upvotes: 1

Related Questions