Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
How to push an object coming from postman to nested object?

I'm having a problem in pushing these data to an nested object.

Here is what I put on postman as JSON format:

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

here is my code on my controller

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


    let product = data.productId;
    let oQuantity = data.quantity
    let totAmount = data.totalAmount


    return  User.findById(product).then(user =>{
    
        user.userOrders.products.push({productId:product})
        user.userOrders.products.push({quantity:oQuantity})

        if (user) {

         return user.save().then((savedOrder,err)=>{
        if (savedOrder) {
            return user
        } else {
            return 'Failed to create order. Please try again'
        }

    })
            
        } else {

            return "try again"
        }
    })
}

my schema is:

userOrders:[
            {
            products:[
                {

                    productName:{
                        type: String,
                        required: [true, "UserId is required"]
                    },

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


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

            PurchasedOn:{
                type: Number,
                default:  new Date()
            }
            
        }
    ]
})

i got these error on my CLI

user.userOrders.products.push({productId:product})
             ^

TypeError: Cannot read properties of null (reading 'userOrders')

Currently i wish to just put these data from postman to the nested object but i think im not using the push use-case well. Any tips?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

user is not found and contains null. User.findById(product) returns an empty result. The ID product can't be found in User. First, check if the user was found, then, push the products:

module.exports.createOrder = async (data) => {
  let product = data.productId;
  let oQuantity = data.quantity
  let totAmount = data.totalAmount

  return User.findById(product).then(user => {
    if (!user) {
      return "try again";
    }
    user.userOrders.products.push({productId:product})
    user.userOrders.products.push({quantity:oQuantity})

    return user.save().then((savedOrder, err) => {
      if (savedOrder) {
        return user;
      } else {
        return 'Failed to create order. Please try again';
      }
    });   
  });
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda