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

158
Visualizações
How do I add a nested object to an object in same schema?

I'm having a difficult time on solving this one. but before that I will show first my controller, route and schema.

Here is my controller:

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

    let id = data.userId;
    

    let oTotal = await User.findById(id).then(total => total.userOrders.subtotal + total.totalAmount)

    User.findById(id).then(user=>{

        user.totalAmount.push({total,oTotal})
        return user.save().then((savedtotal,err)=>{
            if (savedtotal) {
                return savedtotal

            } else {

                return 'Failed to checkout order. Please try again'

            }

        })

})
}

here is my route:

route.get('/checkout',auth.verify,(req,res)=>{
    let token = req.headers.authorization;
    let payload = auth.decode(token)
    let isAdmin = payload.isAdmin
    let id = payload.id
    !isAdmin ? controller.checkoutOrder(id).then(result => 
        res.send(result)) 
    : res.send('Unauthorized User')

})

and the schema:

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

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

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

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

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

when i run a postman get, i receive this error

    let oTotal = await User.findById(id).then(total => total.userOrders.subtotal + total.totalAmount)
                                                             ^

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

I've tried googling how objects work but without requesting from body, I cannot pull "subtotal"(i have values for subtotal) object from "userOrders" to add it to "TotalAmount". Any tips?

about 4 years ago · Juan Pablo Isaza
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