Home > Net >  How to push an object coming from postman as a number(validationError)?
How to push an object coming from postman as a number(validationError)?

Time:02-21

My main problem is I cannot push quantity to its respective object. I am posting data in JSON format in postman like this:

  "productId":"621256596fc0c0ef66bc99ca",
  "quantity":10

my schema is:

userOrders:[
            {
                productId:{
                    type: String,
                    required: [true, "ProductId is required"]
                },

                quantity:{
                    type: Number,
                    required: [true, "Quantity is required"]
                }
            }
        ]

my controller is:

module.exports.createOrder =  async (data) => {

    let id = data.userId;
    let product = data.productId;
    let oQuantity = data.quantity;
    return  User.findById(id).then(user =>{

            
            user.userOrders.push({productId:product})
            user.userOrders.push({quantity:oQuantity})  
            return user.save().then((savedOrder, err) => {
              if (savedOrder) {
                  return savedOrder;
            } else {
                 return 'Failed to create order. Please try again';
            }
         }) 
      });

I receive an error like this:

this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: User validation failed: userOrders.0.quantity: Quantity is required

I've tried so many things but I still cannot solve it. Any tips?

CodePudding user response:

Instead of pushing two seperate objects into the userOrders array, push one object with both properties.

module.exports.createOrder =  async (data) => {

    let id = data.userId;
    let product = data.productId;
    let oQuantity = data.quantity;
    User.findById(id).then(user =>{
            const data = {
              productId: product,
              quantity: oQuantity
            }
            
            user.userOrders.push(data)
            user.save().then((savedOrder, err) => {
              if (savedOrder) {
                  return savedOrder;
            } else {
                 return 'Failed to create order. Please try again';
            }
         }) 
      });

Since the error is a validation error that the Quantity property is required, when you push the two properties as separate object it might be failing the validation as you would then have two separate objects in the userOrders array each only with either productId or quantity

  • Related