Skip to content
Advertisement

Node JS + Mongo DB: ValidationError: User validation failed: username: Path `username` is required because it force replaces the field

I am trying to save my data to a mongodb server but somehow it force replaces the first variable as id so it is throwing the above mentioned error. in router code I am doing console.log(req.body,cred) and here is the result I get:

{ emailAddress: ‘test@gmail.com’, password: ‘123456’, id: ‘6070cbd7c603550ac4385485’ }
{ _id: 6078c61277453c2170d7e177, password: ‘123456’, id: ‘6070cbd7c603550ac4385485’ }

Can you please tell me why it force replaces emailAddresses value with _id ? What am I supposed to do?

User Schema Model

const mongoose = require("mongoose");

const CredSchema = mongoose.Schema({
    id: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
}, {timestamps: true});

// export model user with UserSchema
module.exports = mongoose.model("cred", CredSchema);

Router code

router.post(
    "/credentials",
    [
    ],
    async (req, res) => {

      const errors = validationResult(req);
      try {
        if (!errors.isEmpty()) {
          return res.status(400).json({
            errors: errors.array()
          });
        }

   



       cred = new Cred(req.body);

        console.log(req.body,cred);


     

        await cred.save(); 



        const payload = {
          user: {
            id: cred.id
          }
        };


        jwt.sign(
            payload,
            "randomString",
            {
              expiresIn: 10000
            },
            (err, token) => {
              if (err) throw err;
              res.status(200).json({
                token
              });
            }
        );
      }
        catch (err) {
        console.log(err.message);
        res.status(500).send("Error in Saving");
      }
    }
);

Advertisement

Answer

You don’t have emailAddress in the schema that’s why username is not being saved to db. Either while saving the doc, replace emailAddress with username or replace username with emailAddress in your schema.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement