Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

393
Views
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',
},
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.
      })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!