Search code examples
node.jsmongodbmongoosemongoose-schema

How to ref to multiple models mongoose mongodb


I have 3 models MonthlyMenu. FrozenFood, and DailyDeal.

I'm creating an order model where inside the item field I want to have the id of item which will be from one of the above models.

How can I ref to multiple models in a mongoose schema?

item: {
  type: mongoose.Schema.Types.ObjectId,
  required: true,
  ref: 'DailyDeal',
},

Solution

  • You can use mongoose virtuals for that. First, enable virtuals for your order schema by doing this:

    const order_schema = new mongoose.Schema({
    ...
      item: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
      },
    ...
    },
    {
        toJSON: { virtuals: true }
    });
    

    Then define 3 virtual schemas like so:

    order_schema.virtual('frommonthlymenu', {
        ref: 'monthly_menu', // Your MonthlyMenu model name
        localField: 'item', // Your local field, like a `FOREIGN KEY` in RDS
        foreignField: '_id', // Your foreign field which `localField` links to. Like `REFERENCES` in RDS
        // If `justOne` is true, 'members' will be a single doc as opposed to
        // an array. `justOne` is false by default.
        justOne: true
    });
    
    order_schema.virtual('fromfrozenfood', {
        ref: 'frozen_food',
        localField: 'item',
        foreignField: '_id',
        justOne: true
    });
    
    //Third one here...
    

    Then you can populate frommonthlymenu or fromfrozenfood paths whenever you query your order collection.

    Lead.find(search_filter)
          .populate('frommonthlymenu')
          .populate('fromfrozenfood')
          .then(result => {
              //Whichever path is populated, that's how you know the collection "item" came from.
          })