Search code examples
node.jsmongodbmongoosemongoose-populate

How to 'join' or populate an array


Here is my very basic product schema:

const productSchema = new Schema({
  productName: {
    type: String,
    required: true,
  },
  productDescription: {
    type: String,
  },
  productPrice: {
    type: Number,
  },
});

module.exports = mongoose.model("Product", productSchema);

These products are listed out and a user can add a quantity for each. I am storing in an array of objects as per below. I want to join these two collections together so that I can output the qty of products selected by the user. I believe I need to use populate here but not sure how to set up the Refs and so on.

const PartySchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  catering: [{ id: mongoose.Types.ObjectId, qty: Number }],
  created_at: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("Party", PartySchema);

Solution

  • I'm sharing this solution with the assumption that the catering field is the sub-document array pointing to the Product Schema:

    The Product Schema is fine so it stays the same (although to keep to convention I would advice naming your schema 'Products' instead of 'Product', Mongo Naming Covention):

    const productSchema = new Schema({
      productName: {
        type: String,
        required: true,
      },
      productDescription: {
        type: String,
      },
      productPrice: {
        type: Number,
      },
    });
    
    module.exports = mongoose.model("Products", productSchema);

    And next the Party Schema would be:

    const PartySchema = new Schema({
      firstName: {
        type: String,
        required: true,
      },
      lastName: {
        type: String,
        required: true,
      },
      catering: [{
        id: {
        type: mongoose.Types.ObjectId,
        ref: 'Products',
      },
        qty: {
        type: Number,
      }
      }],
      created_at: {
        type: Date,
        default: Date.now,
      },
    });
    
    module.exports = mongoose.model("Parties", PartySchema);