Monday, 8 May 2017

Mongoose schema validations not running on update

I'm having difficulty running validations when I'm updating a document with mongoose. Can someone take a look and help me out? I'm using async await as well.

Here is my schema:

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;

And here is my update endpoint.

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();
    return res.status(200).json();
  } catch(error){
    console.log(error);
    return res.status(500).json({ error });
  }
};

No validations are being run at all. Help me out please. I've been stuck on this for an hour and a half.



via Nate

No comments:

Post a Comment