node.jsdatabasemongodbexpressthunderclient

Thunderl Cient- Error: User validation failed: accountStatus: `SUSPEND` is not a valid enum value for path `accountStatus`., roles.0:


When I hit the route from Thunder Client the following error comes to my windows

{
  "message": "Server Error Occurred"
}

enter image description here

Error: User validation failed: accountStatus: SUSPEND is not a valid enum value for path accountStatus., roles.0: ADMINISTRATOR is not a valid enum value for path roles.0.

    at ValidationError.inspect (D:\server\node_modules\mongoose\lib\error\validation.js:50:26)      
    at formatValue (node:internal/util/inspect:805:19)
    at inspect (node:internal/util/inspect:364:10)
    at formatWithOptionsInternal (node:internal/util/inspect:2298:40)
    at formatWithOptions (node:internal/util/inspect:2160:10)
    at console.value (node:internal/console/constructor:342:14)
    at console.log (node:internal/console/constructor:379:61)
    at D:\server.js:97:13
    at Layer.handle_error (D:\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (D:\node_modules\express\lib\router\index.js:326:13) {
  errors: {
    accountStatus: ValidatorError: `SUSPEND` is not a valid enum value for path `accountStatus`.
        at validate (D:\node_modules\mongoose\lib\schemaType.js:1385:13)
        at SchemaType.doValidate (D:\node_modules\mongoose\lib\schemaType.js:1369:7)
        at D:\node_modules\mongoose\lib\document.js:3042:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'enum',
      path: 'accountStatus',
      value: 'SUSPEND',
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    },
    'roles.0': ValidatorError: `ADMINISTRATOR` is not a valid enum value for path `roles.0`.
        at validate (D:\node_modules\mongoose\lib\schemaType.js:1385:13)
        at SchemaType.doValidate (D:\node_modules\mongoose\lib\schemaType.js:1369:7)
        at D:\node_modules\mongoose\lib\document.js:3042:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: [Object],
      kind: 'enum',
      path: 'roles.0',
      value: 'ADMINISTRATOR',
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    }
  },
  _message: 'User validation failed'
}

Server

app.post('/register', async (req, res, next) => {
    //console.log(req.body);
    const { name, email, password, roles, accountStatus } = req.body;         

    if (!email || !password) {               
        return res.status(400).json({ message: "Invalid Data" })
    }

    try {
        let userEmail = await User.findOne({ email })
        console.log(userEmail);
        if (userEmail) {
            return res.status(201).json({ message: "User already exists" })
        }

        user = new User({ name, email, password, roles, accountStatus });     

        const salt = await bcrypt.genSalt(10);          
        const hash = await bcrypt.hash(password, salt);
        user.password = hash;

        await user.save();
        return res.status(200).json({ message: "User created successfully", user })
    } catch (error) {
        next(error);
    }
});

Database

const { model, Schema } = require('mongoose');

const userSchema = new Schema({
    name: {
        type: String,
        required: true,
        minlength: 3,
        maxlength: 10,
    },
    email: {
        type: String,
        required: true,
        validate: {
            validator: function (v) {
                return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
            },
            message: (prop) => `Invalid Email: ${prop.value}`,
        },
    },
    password: {
        type: String,
        minlength: [6, 'Password is too short'],
        required: true,
    },
    roles: {
        type: [String],
        enum: ['STUDENT', 'ADMIN', 'USER'],
        default: ['STUDENT'],               
        required: true,
    },
    accountStatus: {
        type: String,
        enum: ['PENDING', 'ACTIVE', 'REJECTED'],
        default: ['PENDING'],
        required: true,
    },
});

const User = model('User', userSchema);

module.exports = User;

I am trying to change JSON format several times, but get the error


Solution

  • accountStatus: ValidatorError: SUSPEND is not a valid enum value ?

    Because you are defined ['PENDING', 'ACTIVE', 'REJECTED'] as valid enums that why it's throwing an error. Try to pass any one of this.

    accountStatus: {
         type: String,
         enum: ['PENDING', 'ACTIVE', 'REJECTED'],
         default: ['PENDING'],
         required: true,
     }