0

I have an order model/schema, and my goal is that in this model in "list", I receive the information from the model cart in array format. How could I do this using ref?

cart model

const mongoose = require('mongoose');

const CartSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        note: {
            type: String,
            required: true,
        },
        price: {
            type: Number,
            required: false,
        },
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Cart", CartSchema);

order

const mongoose = require('mongoose');

const OrderSchema = new mongoose.Schema(
    {
        list: {
            name: String,
            notes: String,
        },
        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);

Basically receive in array format the information of the model cart in "list" in model order

1 Answer 1

1

You should define your list as an array of ObjectIds referring to the Cart model:

const OrderSchema = new mongoose.Schema(
  {
      list: [{
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Cart'
      }],
      ...
  });

Then, to retrieve the values in list, just populate the Order:

Order.find({}).populate('list').exec();
Sign up to request clarification or add additional context in comments.

6 Comments

Can I send several "cart" within the list?
For example, can I send more than one cart to this array that will be added? Or just one?
list is declared as an array so yes, you can add multiple Cart references to it
How can I do this in postman? For example
In theory in "list" I should put the cart id I want, right? If I want more than one cart, how can I add more than one id? (postman)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.