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?