I have a model called order that has a property orderItem. orderItem is of type id orderItem here's an extract of the schema.
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
orderItems: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'OrderItem',
required: true
}],
shippingAddress1: {
type: String,
required: true,
},
I create the order item first and then save the collection of order items as part of the new Order that I want to save. Done like this:
const orderItemsIds = Promise.all(req.body.orderItems.map(async orderItem => {
let newOrderItem = new OrderItem({
quantity: orderItem.quantity,
product: orderItem.product
})
newOrderItem = await newOrderItem.save();
return newOrderItem._id;
}))
try {
const resolvedOrderItemsIds = await orderItemsIds;
console.log(resolvedOrderItemsIds);
let order = new Order({
orderItems: resolvedOrderItemsIds,
...
})
// order = await order.save();
order.save(function (err) {
if(!order) {
return res.status(400).send('The order cannot be created!');
}
return res.status(201).send({'message': 'Order Created', order});
})
} catch (error) {
}
})
The OrderItems and Order are created and I get a response in PostMan that everything is created. I see results like this:
{
"message": "Order Created",
"order": {
"orderItems": [
"615562ab6c7cd7021c7e37f7",
"615562ab6c7cd7021c7e37f8"
],
"shippingAddress1": "21 sample street",
"shippingAddress2": "Sample Bus Stop",
"city": "Sample",
"zip": "100001",
"country": "Sample",
"status": "Pending",
"user": "6151a6d7f6d3b96060f0aec5",
"_id": "615562ab6c7cd7021c7e37fb",
"dateOrdered": "2021-09-30T07:09:31.493Z",
"id": "615562ab6c7cd7021c7e37fb"
}
}
What amuses me is that the Order does not get saved in MongoDB. Can I know what I am doing wrongly?
Turns out I was missing a required field when building the request body and there was no form of information about this after posting the request with the way I did it. I found out about my missing field when I saved the item like this:
await order.save().then(item => {
return res.status(201).send({'message': 'Order Created', item});
}).catch(err => {
res.status(400).send({"message": 'The order cannot be created!', "error": err});
})