PUSH id in order like add to cart

Viewed 26

I created model schema for users and products with simple CRUD, my next project is my model schema order where I push my userId and projectId in the array in order.

this is the code that I created in the controller

module.exports.makeOrders = (reqBody) => {

let newOrder = new Order({
    totalAmount : reqBody.totalAmount,
    usersOrder.push({
        userId : reqBody.userId,
        project : reqBody.projectId
    }),
})

return newOrder.save().then((order, error) =>{
    if(error){
        return false;
    }
    else{ 
        return true;
    }
})
}

and this is my route

router.post("/checkout", (req, res) => {
let data = {
    userId : req.body.userId,
    productId : req.body.productId
}
userController.makeOrders(data).then(resultFromController => res.send(resultFromController))
})

this is my model

const orderSchema = new mongoose.Schema({
totalAmount : {
    type : Number,
    required : true
},
purchasedOn : {
    type : Date,
    default : new Date
},
usersOrder :[
                {
                    userId : {
                        type : String,
                        required : true
                },

                    productId : {
                        type : String,
                        required : true
                },
            }
        ]
    })

this is what I enter in postman

{
"totalAmount" : 1000,
"userId" : "62a9c46c4d15dc8157c375aa",
"productId" : "62aafe01d9337ce87ff5aaa1"
}

the error that I'm experiencing is "SyntaxError: Unexpected token '.' " based on what I know I put the push method in the wrong place. I just copy the create method in the user which is working. I don't know why it is not working in order controller. Note. I just started to learn json.

1 Answers

You have to update your routes like this as you are missing the totalAmount field and inside your schema you mentioned it as required fields.

router.post("/checkout", (req, res) => {
let data = {
    userId : req.body.userId,
    productId : req.body.productId,
    totalAmount: req.body.totalAmount

}
userController.makeOrders(data).then(resultFromController => res.send(resultFromController))
})
Related