如何使用猫鼬将 CartItem 架构产品详细信息填充到订单架构中

问题描述

我想在我的订单中填充产品的详细信息。目前它只在产品数组中添加产品 ID。我尝试了几种方法,但似乎都不起作用。

import mongoose from 'mongoose'
const CartItemSchema = new mongoose.Schema({
  product: {type: mongoose.Schema.ObjectId,ref: 'Product'},quantity: Number,shop: {type: mongoose.Schema.ObjectId,ref: 'Shop'},status: {type: String,default: 'Not processed',enum: ['Not processed','Processing','Shipped','Delivered','Cancelled']}
})
const CartItem = mongoose.model('CartItem',CartItemSchema)
const OrderSchema = new mongoose.Schema({
  products: [CartItemSchema],customer_name: {
    type: String,trim: true,required: 'Name is required'
  },customer_email: {
    type: String,match: [/.+\@.+\..+/,'Please fill a valid email address'],required: 'Email is required'
  },delivery_address: {
    street: {type: String,required: 'Street is required'},city: {type: String,required: 'City is required'},state: {type: String},zipcode: {type: String,required: 'Zip Code is required'},country: {type: String,required: 'Country is required'}
  },payment_id: {},updated: Date,created: {
    type: Date,default: Date.Now
  },user: {type: mongoose.Schema.ObjectId,ref: 'User'}
})

const Order = mongoose.model('Order',OrderSchema)

export {Order,CartItem}

我尝试这样做:

const create = async (req,res) => {
  try {
    req.body.order.user = req.profile;
    console.log(req);
    let order = new Order(req.body.order);

    let neworder = await Order.findById(order._id)
      .populate("products.product","name price")
      .populate("products.shop","name")
      .exec();
    // console.log(order);
    let result = await order.save();
    sendMail(order);

    res.status(200).json(result);
  } catch (err) {
    return res.status(400).json({
      error: errorHandler.getErrorMessage(err),});
  }
};

也尝试使用它来填充产品详细信息,但似乎不起作用!

Order.findById(order._id).populate({ path: "products.product",select: "_id name price" })

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)