0

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?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

i want to a create order in post methoad

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.