我正在嘗試在 post 方法中創建訂單。我有兩個檔案 - 訂單、訂單項。模式是 -
var OrderSchema = new Schema({
name: String,
orderItems : [{ type: Schema.Types.ObjectId, ref: 'orderitems' }]
});
var orderItemsSchema = new Schema({
name: String,
products : String
});
我的控制器功能——
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);
我想下訂單。req.body 資料是——
{
"orderItems" : [
{
"quantity": 3,
"product" : "Orange"
},
{
"quantity": 2,
"product" : "Banana"
}
],
"phone": " 420702241333",
}
我該如何解決這個問題?
uj5u.com熱心網友回復:
我了解您需要從 ref 獲取 orderItems 嗎?如果那你可以使用填充
order.populate('orderItems')
//編輯
首先需要你的模型從 monngoose 之后進行 insertMany 或保存 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410945.html
標籤:
上一篇:插入資料的貓鼬觸發器
下一篇:通過貓鼬中的函式進行嵌套資料收集
