0

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.

For clarifications. I'm using v4.9.8 of mongoose.

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

When i do a console.log on results all i get is this { n: 1, nModified: 1, ok: 1 } No validations are being run at all. Help me out please. I've been stuck on this for an hour and a half.

2 Answers2

0

If you mean that the unique validations aren't being run, notice the following:

For technical reasons, this plugin requires that you also set the context option to query.

So:

const opts = { runValidators: true, context : 'query' };
robertklep
  • 198,204
  • 35
  • 394
  • 381
0

Mongoose and middleware doesn't get executed during an update as that's basically a pass-through to the native driver for old mongoose versions. Refer to this link to get a detailed answer.

Later on, Mongoose 4.0 introduced an option to run validators on update() and findOneAndUpdate() calls. Turning this option on will run validators for all fields that your update() call tries to $set or $unset.

You can also try this package which deals with your problem.

Community
  • 1
  • 1
node_saini
  • 727
  • 1
  • 6
  • 22