How to create array of object ids in ref mongoose?
I am trying to create an order in the post method. I have two documents - Order, OrderItem. Schemas are-
var OrderSchema = new Schema({
name: String,
orderItems : [{ type: Schema.Types.ObjectId, ref: 'orderitems' }]
});
var orderItemsSchema = new Schema({
name: String,
products : String
});
My controller function --
let itemArr: any[] = [];
req.body.orderItems.map(async (item: { products: any; quantity: any }) => {
const newOrdeItem = new OrderItems({
products: item.products,
quantity: item.quantity,
});
const items = await newOrdeItem.save();
//found ids
itemArr.push(items._id);
});
//not found ids
itemArr.push(items._id);
const newOrder = new Order({
orderItems: itemArr,
phone: req.body.phone,
});
const order = await newOrder.save();
return res.json(order);
I want to make an order. req.body data are--
{
"orderItems" : [
{
"quantity": 3,
"product" : "Orange"
},
{
"quantity": 2,
"product" : "Banana"
}
],
"phone": "+420702241333",
}
How can I solve this issue?
I understand you need to get the orderItems from the ref ? if that can you use populate
order.populate('orderItems')
//Edit
frist require your model from monngoose after that make insertMany or save fn like
const dbOrders = require('pathOfModel')
orderResult = await dbOrders.insertMany({
name : req.body.name || 'Name you need insert in Schema',
orderItems : itemArr
})
console.log(orderResult) // res.json(orderResult)