【问题标题】:How to create array of object ids in ref mongoose?如何在 ref mongoose 中创建对象 ID 数组?
【发布时间】:2022-01-12 14:40:44
【问题描述】:

我正在尝试在 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",
}

我该如何解决这个问题?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    我知道您需要从 ref 获取 orderItems 吗?如果那你可以使用填充

    order.populate('orderItems')
    

    //编辑

    首先需要你的模型来自 monngoose 之后进行 insertMany 或保存 fn 喜欢

       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)
    

    【讨论】:

    • 我想在 post 方法中创建订单
    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2017-10-15
    • 2013-05-14
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2013-04-25
    • 2016-07-28
    相关资源
    最近更新 更多