0

I'm trying to create an order controller where I would like to store in an array other "cart" models by reference, as in "list":

const mongoose = require('mongoose');

const OrderSchema = new mongoose.Schema(
    {
        list: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Cart',
        }],
        totalAmount: {
            type: Number,
            required: true,
        },
        payment: {
            type: String,
            required: true,
        },
        address: {
            type: String,
            required: true,
        },
        addressNote: {
            type: String,
            required: false,
        },
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Order", OrderSchema);

I can store the cart ids in the list and ok, but the problem is that when I do a get from order, I would like the list to return what is in the cart and not the ids that I sent

show all order controller:

const Order = require('../../models/Order');

class ShowAllProduct {
    async show(req, res) {

        try {
            const order = await Order.find({}).populate('list').exec();

            return res.status(200).json(order);
        } catch (err) {
            return res.status(500).json(err);
        }
    }
} 

module.exports = new ShowAllProduct();

I tried to do this through the populate method, but without success.

Routfin
  • 397
  • 1
  • 11
  • Are you getting an error while executing the `populate` method. This is how we usually replace the reference ids with the actual elements. – Dan Philip Bejoy Nov 21 '22 at 15:35

1 Answers1

1

try this way to populate

const order = await Order.find({}).populate({
   path:'list',
   model:'Cart'
}).lean();

update : if you want to populate Product model from Cart model ,

const order = await Order.find({}).populate({
       path:'list',
       model:'Cart',
       populate:{
          path:'product', // field name of product in Cart model
          model:'Product'
       }
    }).lean();

use select:'name image_url' inside populate if you want to select only specific fields from model .

const order = await Order.find({}).populate({
           path:'list',
           model:'Cart',
           populate:{
              path:'product', // field name of product in Cart model
              model:'Product',
              select:'name image_url'
           }
        }).lean();
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
  • Thanks, another question... Inside "cart" I have a name that receives the ref of another "product" model, would I be able to return the product name from the cart id and also the product name inside the cart inside the order controller? – Routfin Nov 21 '22 at 16:02