Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make mongoDB return the item from inside the array through the id?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

try this way to populate

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading