1

i'm trying to generate array of errors based on certain conditions , how can i achieve that , postman arrises this : "Cannot read properties of undefined (reading 'push')"

  username: {
    type: String,
    required: [true, "username is required"],
    // minlength: 6,
    unique: true,
    // match: [
    //   /^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/,
    //   "username shouldn't include . or _ and at least 3 letters and at maximum 20 letters",
    // ],
    validate: {
      errors: [],
      validator: function (username) {
        if (username.length < 10) {
          this.errors.push("username cannot be less than 3 characters");
        }
        if (username.match(/(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/)) {
          this.errors.push(`username shouldn't begin or end with . or _ `);
        }
      },
      message: this.errors,
    },
  },

1 Answer 1

1

Create an array in the validator function and throw this array as new Error(). Then use this array in the callback of the save() function.

validate

validate: {
        validator: function (username) {
            let errors = []
            if (username.length < 3)
                errors.push("username cannot be less than 3 characters")

            if (username.match(/(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/))
                errors.push("username shouldn't begin or end with . or _ ")

            if (errors.length > 0)
                throw new Error(errors)
        }
    }

save

newUser.save((err, user) => {
    if (err) {
        let errors = Object.values(err.errors)[0].properties.message.split(',')
        return res.status(400).json({
            success: false,
            err: errors.length > 1 ? errors : errors[0]
        })
    }
    else ...
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.